antipatterns.rs 8.3 KB

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