antipatterns.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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 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. //! - Understanding 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, stable ID 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. fn AntipatternNoKeys(cx: Scope<NoKeysProps>) -> Element {
  35. // WRONG: Make sure to add keys!
  36. cx.render(rsx! {
  37. ul {
  38. cx.props.data.iter().map(|(k, v)| rsx!(li { "List item: {v}" }))
  39. }
  40. });
  41. // RIGHT: Like this:
  42. cx.render(rsx! {
  43. ul {
  44. cx.props.data.iter().map(|(k, v)| rsx!(li { key: "{k}", "List item: {v}" }))
  45. }
  46. })
  47. }
  48. /// Antipattern: Deeply nested fragments
  49. /// ------------------------------------
  50. ///
  51. /// This particular antipattern is not necessarily an antipattern in other frameworks but does has a performance impact
  52. /// in Dioxus apps. Fragments don't mount a physical element to the DOM immediately, so Dioxus must recurse into its
  53. /// children to find a physical DOM node. This process is called "normalization". Other frameworks perform an agressive
  54. /// mutative normalization while Dioxus keeps your VNodes immutable. This means that deeply nested fragments make Dioxus
  55. /// perform unnecessary work. Prefer one or two levels of fragments / nested components until presenting a true DOM element.
  56. ///
  57. /// Only Component and Fragment nodes are susceptible to this issue. Dioxus mitigates this with components by providing
  58. /// an API for registering shared state without the ContextProvider pattern.
  59. fn AntipatternNestedFragments(cx: Scope<()>) -> Element {
  60. // Try to avoid heavily nesting fragments
  61. cx.render(rsx!(
  62. Fragment {
  63. Fragment {
  64. Fragment {
  65. Fragment {
  66. Fragment {
  67. div { "Finally have a real node!" }
  68. }
  69. }
  70. }
  71. }
  72. }
  73. ))
  74. }
  75. /// Antipattern: Using state after it's been updated
  76. /// -----------------------------------------------
  77. ///
  78. /// This is an antipattern in other frameworks, but less so in Dioxus. However, it's important to highlight that use_state
  79. /// does *not* work the same way as it does in React. Rust provides explicit guards against mutating shared data - a huge
  80. /// problem in JavaScript land. With Rust and Dioxus, it's nearly impossible to misuse `use_state` - you simply can't
  81. /// accidentally modify the state you've received!
  82. ///
  83. /// However, calling set_state will *not* update the current version of state in the component. This should be easy to
  84. /// recognize from the function signature, but Dioxus will not update the "live" version of state. Calling `set_state`
  85. /// merely places a new value in the queue and schedules the component for a future update.
  86. fn AntipatternRelyingOnSetState(cx: Scope) -> Element {
  87. let (state, set_state) = use_state(&cx, || "Hello world").classic();
  88. set_state("New state");
  89. // This will return false! `state` will *still* be "Hello world"
  90. assert!(state == &"New state");
  91. todo!()
  92. }
  93. /// Antipattern: Capitalization
  94. /// ---------------------------
  95. ///
  96. /// This antipattern is enforced to retain parity with other frameworks and provide useful IDE feedback, but is less
  97. /// critical than other potential misuses. In short:
  98. /// - Only raw elements may start with a lowercase character
  99. /// - All components must start with an uppercase character
  100. ///
  101. /// i.e.: the following component will be rejected when attempted to be used in the rsx! macro
  102. static antipattern_component: Component = |cx| todo!();
  103. /// Antipattern: Misusing hooks
  104. /// ---------------------------
  105. ///
  106. /// This pattern is an unfortunate one where Dioxus replicates the same behavior as other frameworks. Dioxus supports
  107. /// "hooks" - i.e. "memory cells" that allow a value to be stored between renders. This allows other hooks to tap into
  108. /// a component's "memory" without explicitly adding all of its data to a struct definition. In Dioxus, hooks are allocated
  109. /// with a bump arena and then immediately sealed.
  110. ///
  111. /// This means that hooks may not be misused:
  112. /// - Called out of order
  113. /// - Called in a conditional
  114. /// - Called in loops or callbacks
  115. ///
  116. /// For the most part, Rust helps with rule #3 but does not save you from misusing rule #1 or #2. Dioxus will panic
  117. /// if hooks do not downcast to the same data between renders. This is validated by TypeId and, eventually, a custom key.
  118. #[derive(PartialEq, Props)]
  119. struct MisuedHooksProps {
  120. should_render_state: bool,
  121. }
  122. fn AntipatternMisusedHooks(cx: Scope<MisuedHooksProps>) -> Element {
  123. if props.should_render_state {
  124. // do not place a hook in the conditional!
  125. // prefer to move it out of the conditional
  126. let (state, set_state) = use_state(&cx, || "hello world").classic();
  127. cx.render(rsx!(div { "{state}" }))
  128. } else {
  129. cx.render(rsx!(div { "Not rendering state" }))
  130. }
  131. }
  132. /// Antipattern: Downcasting refs and panicking
  133. /// ------------------------------------------
  134. ///
  135. /// Occasionally it's useful to get the ref of an element to handle it directly. Elements support downcasting to
  136. /// Dioxus' virtual element types as well as their true native counterparts. Downcasting to Dioxus' virtual elements
  137. /// will never panic, but downcasting to native elements will fail if on an unsupported platform. We recommend avoiding
  138. /// publishing hooks and components that deeply rely on controlling elements using their native `ref`, preferring to
  139. /// use their Dioxus Virtual Element counterpart instead.
  140. /// This particular code *will panic* due to the unwrap. Try to avoid these types of patterns.
  141. /// ---------------------------------
  142. /// TODO: Get this to compile properly
  143. /// let div_ref = use_node_ref(&cx);
  144. ///
  145. /// cx.render(rsx!{
  146. /// div { ref: div_ref, class: "custom class",
  147. /// button { "click me to see my parent's class"
  148. /// onclick: move |_| if let Some(div_ref) = div_ref {
  149. /// panic!("Div class is {}", div_ref.to_native::<web_sys::Element>().unwrap().class())
  150. /// }
  151. /// }
  152. /// }
  153. /// })
  154. static _example: Component = |cx| todo!();
  155. /// Antipattern: publishing components and hooks with all features enabled
  156. /// ----------------------------------------------------------------------
  157. ///
  158. /// The `dioxus` crate combines a bunch of useful utilities together (like the rsx! and html! macros, hooks, and more).
  159. /// However, when publishing your custom hook or component, we highly advise using only the `core` feature on the dioxus
  160. /// crate. This makes your crate compile faster, makes it more stable, and avoids bringing in incompatible libraries that
  161. /// might make it not compile on unsupported platforms.
  162. ///
  163. /// We don't have a code snippet for this, but just prefer to use this line:
  164. /// dioxus = { version = "*", features = ["core"]}
  165. /// instead of this one:
  166. /// dioxus = { version = "*", features = ["web", "desktop", "full"]}
  167. /// in your Cargo.toml
  168. ///
  169. /// This will only include the `core` dioxus crate which is relatively slim and fast to compile and avoids target-specific
  170. /// libraries.
  171. static __example: Component = |cx| todo!();
  172. fn Example(cx: Scope) -> Element {
  173. cx.render(rsx! {
  174. AntipatternNoKeys { data: std::collections::HashMap::new() }
  175. AntipatternNestedFragments {}
  176. })
  177. }