antipatterns.rs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. //! Example: Antipatterns
  2. //! ---------------------
  3. //!
  4. //! This example shows what *not* to do and provides a reason why a given pattern is considered an "AntiPattern". Most
  5. //! anti-patterns are considered wrong to due performance reasons or violate the "rules" of Dioxus. These rules are
  6. //! borrowed from other successful UI frameworks, and Dioxus is more focused on providing a familiar, ergonomic interface
  7. //! rather than building new harder-to-misuse patterns.
  8. //!
  9. //! In this list we showcase:
  10. //! - Not adding keys for iterators
  11. //! - Heavily nested fragments
  12. //! - Understadning ordering of set_state
  13. //! - Naming conventions
  14. //! - Rules of hooks
  15. //!
  16. //! Feel free to file a PR or Issue if you run into another antipattern that you think users of Dioxus should know about.
  17. use dioxus::prelude::*;
  18. /// Antipattern: Iterators without keys
  19. /// -----------------------------------
  20. ///
  21. /// This is considered an anti-pattern for performance reasons. Dioxus will diff your current and old layout and must
  22. /// take a slower path if it can't correlate old elements with new elements. Lists are particularly susceptible to the
  23. /// "slow" path, so you're strongly encouraged to provide a unique ID stable between renders. Additionally, providing
  24. /// the *wrong* keys is even worse - props might be assigned to the wrong components! Keys should be:
  25. /// - Unique
  26. /// - Stable
  27. /// - Predictable
  28. ///
  29. /// Dioxus will log an error in the console if it detects that your iterator does not properly generate keys
  30. #[derive(PartialEq, Props)]
  31. struct NoKeysProps {
  32. data: std::collections::HashMap<u32, String>,
  33. }
  34. static AntipatternNoKeys: FC<NoKeysProps> = |cx| {
  35. // WRONG: Make sure to add keys!
  36. rsx!(in cx, ul {
  37. {cx.data.iter().map(|(k, v)| rsx!(li { "List item: {v}" }))}
  38. });
  39. // RIGHT: Like this:
  40. rsx!(in cx, ul {
  41. {cx.data.iter().map(|(k, v)| rsx!(li { key: "{k}", "List item: {v}" }))}
  42. })
  43. };
  44. /// Antipattern: Deeply nested fragments
  45. /// ------------------------------------
  46. ///
  47. /// This particular antipattern is not necessarily an antipattern in other frameworks but does has a performance impact
  48. /// in Dioxus apps. Fragments don't mount a physical element to the dom immediately, so Dioxus must recurse into its
  49. /// children to find a physical dom node. This process is called "normalization". Other frameworks perform an agressive
  50. /// mutative normalization while Dioxus keeps your VNodes immutable. This means that deepely nested fragments make Dioxus
  51. /// perform unnecessary work. Prefer one or two levels of fragments / nested components until presenting a true dom element.
  52. ///
  53. /// Only Component and Fragment nodes are susceptible to this issue. Dioxus mitigates this with components by providing
  54. /// an API for registering shared state without the ContextProvider pattern.
  55. static AntipatternNestedFragments: FC<()> = |cx| {
  56. // Try to avoid heavily nesting fragments
  57. rsx!(in cx,
  58. Fragment {
  59. Fragment {
  60. Fragment {
  61. Fragment {
  62. Fragment {
  63. div { "Finally have a real node!" }
  64. }
  65. }
  66. }
  67. }
  68. }
  69. )
  70. };
  71. /// Antipattern: Using state after its been updated
  72. /// -----------------------------------------------
  73. ///
  74. /// This is an antipattern in other frameworks, but less so in Dioxus. However, it's important to highlight that use_state
  75. /// does *not* work the same way as it does in React. Rust provides explicit guards against mutating shared data - a huge
  76. /// problem in JavaScript land. With Rust and Dioxus, it's nearly impossible to misuse `use_state` - you simply can't
  77. /// accidentally modify the state you've received!
  78. ///
  79. /// However, calling set_state will *not* update the current version of state in the component. This should be easy to
  80. /// recognize from the function signature, but Dioxus will not update the "live" version of state. Calling `set_state`
  81. /// merely places a new value in the queue and schedules the component for a future update.
  82. static AntipaternRelyingOnSetState: FC<()> = |cx| {
  83. let (state, set_state) = use_state(cx, || "Hello world").classic();
  84. set_state("New state");
  85. // This will return false! `state` will *still* be "Hello world"
  86. assert!(state == &"New state");
  87. todo!()
  88. };
  89. /// Antipattern: Capitalization
  90. /// ---------------------------
  91. ///
  92. /// This antipattern is enforced to retain parity with other frameworks and provide useful IDE feedback, but is less
  93. /// critical than other potential misues. In short:
  94. /// - Only raw elements may start with a lowercase character
  95. /// - All components must start with an uppercase character
  96. ///
  97. /// IE: the following component will be rejected when attempted to be used in the rsx! macro
  98. static antipattern_component: FC<()> = |cx| todo!();
  99. /// Antipattern: Misusing hooks
  100. /// ---------------------------
  101. ///
  102. /// This pattern is an unfortunate one where Dioxus supports the same behavior as in other frameworks. Dioxus supports
  103. /// "hooks" - IE "memory cells" that allow a value to be stored between renders. This allows other hooks to tap into
  104. /// a components "memory" without explicitly adding all of its data to a struct definition. In Dioxus, hooks are allocated
  105. /// with a bump arena and then immediately sealed.
  106. ///
  107. /// This means that hooks may not be misued:
  108. /// - Called out of order
  109. /// - Called in a conditional
  110. /// - Called in loops or callbacks
  111. ///
  112. /// For the most part, Rust helps with rule #3 but does not save you from misusing rule #1 or #2. Dioxus will panic
  113. /// if hooks do not downcast the same data between renders. This is validated by TypeId - and eventually - a custom key.
  114. #[derive(PartialEq, Props)]
  115. struct MisuedHooksProps {
  116. should_render_state: bool,
  117. }
  118. static AntipatternMisusedHooks: FC<MisuedHooksProps> = |cx| {
  119. if cx.should_render_state {
  120. // do not place a hook in the conditional!
  121. // prefer to move it out of the conditional
  122. let (state, set_state) = use_state(cx, || "hello world").classic();
  123. rsx!(in cx, div { "{state}" })
  124. } else {
  125. rsx!(in cx, div { "Not rendering state" })
  126. }
  127. };
  128. /// Antipattern: Downcasting refs and panicing
  129. /// ------------------------------------------
  130. ///
  131. /// Occassionally it's useful to get the ref of an element to handle it directly. Elements support downcasting to
  132. /// Dioxus's virtual element types as well as their true native counterparts. Downcasting to Dioxus' virtual elements
  133. /// will never panic, but downcasting to native elements will fail if on an unsupported platform. We recommend avoiding
  134. /// publishing hooks and components that deply rely on control over elements using their native `ref`, preferring to
  135. /// use their Dioxus Virtual Element counterpart instead.
  136. // This particular code *will panic* due to the unwrap. Try to avoid these types of patterns.
  137. /// ---------------------------------
  138. /// TODO: Get this to compile properly
  139. /// let div_ref = use_node_ref(&cx);
  140. ///
  141. /// cx.render(rsx!{
  142. /// div { ref: div_ref, class: "custom class",
  143. /// button { "click me to see my parent's class"
  144. /// onclick: move |_| if let Some(div_ref) = div_ref {
  145. /// panic!("Div class is {}", div_ref.to_native::<web_sys::Element>().unwrap().class())
  146. /// }
  147. /// }
  148. /// }
  149. /// })
  150. static _example: FC<()> = |cx| todo!();
  151. /// Antipattern: publishing components and hooks with all features enabled
  152. /// ----------------------------------------------------------------------
  153. ///
  154. /// The `dioxus` crate combines a bunch of useful utilities together (like the rsx! and html! macros, hooks, and more).
  155. /// However, when publishing your custom hook or component, we highly advise using only the `core` feature on the dioxus
  156. /// crate. This makes your crate compile faster, makes it more stable, and avoids bringing in incompatible libraries that
  157. /// might make it not compile on unsupported platforms.
  158. ///
  159. /// We don't have a code snippet for this, but just prefer to use this line:
  160. /// dioxus = { version = "*", features = ["core"]}
  161. /// instead of this one:
  162. /// dioxus = { version = "*", features = ["web", "desktop", "full"]}
  163. /// in your Cargo.toml
  164. ///
  165. /// This will only include the `core` dioxus crate which is relatively slim and fast to compile and avoids target-specific
  166. /// libraries.
  167. static __example: FC<()> = |cx| todo!();
  168. pub static Example: FC<()> = |cx| {
  169. cx.render(rsx! {
  170. AntipatternNoKeys { data: std::collections::HashMap::new() }
  171. AntipatternNestedFragments {}
  172. })
  173. };