feat(docs): Improved shared state, use_effect and use_memo docs

This commit is contained in:
marc2332 2023-06-28 00:15:00 +02:00
parent dfa4d8d989
commit 8a2f9f3fcb
No known key found for this signature in database
GPG key ID: C06A66E2828F72E1
7 changed files with 158 additions and 19 deletions

View file

@ -21,10 +21,12 @@
- [Hooks & Component State](interactivity/hooks.md) - [Hooks & Component State](interactivity/hooks.md)
- [User Input](interactivity/user_input.md) - [User Input](interactivity/user_input.md)
- [Sharing State](interactivity/sharing_state.md) - [Sharing State](interactivity/sharing_state.md)
- [Memoization](interactivity/memoization.md)
- [Custom Hooks](interactivity/custom_hooks.md) - [Custom Hooks](interactivity/custom_hooks.md)
- [Dynamic Rendering](interactivity/dynamic_rendering.md) - [Dynamic Rendering](interactivity/dynamic_rendering.md)
- [Routing](interactivity/router.md) - [Routing](interactivity/router.md)
- [Async](async/index.md) - [Async](async/index.md)
- [UseEffect](async/use_effect.md)
- [UseFuture](async/use_future.md) - [UseFuture](async/use_future.md)
- [UseCoroutine](async/use_coroutine.md) - [UseCoroutine](async/use_coroutine.md)
- [Spawning Futures](async/spawn.md) - [Spawning Futures](async/spawn.md)

View file

@ -0,0 +1,32 @@
# UseEffect
[`use_effect`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_effect.html) provides a future that executes after the hooks have been applied.
Whenever the hooks dependencies change, the future will be re-evaluated. This is useful to syncrhonize with external events.
If a future is pending when the dependencies change, the previous future will be allowed to continue
> The `dependencies` is tuple of references to values that are `PartialEq + Clone`.
```rust, no_run
#[inline_props]
fn Profile(cx: Scope, id: &str) -> Element {
let name = use_state(cx, || "Default name");
// Only fetch the user data when the id changes.
use_effect(cx, (id,), |(id,)| async move {
let user = fetch_user(id).await;
name.set(user.name);
});
render!(
p { "{name}" }
)
}
fn app(cx: Scope) -> Element {
render!(
Profile { id: "dioxusLabs" }
)
}
```

View file

@ -0,0 +1,23 @@
# Memoization
[`use_memo`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_memo.html) let's you memorize values and therefore save computation time. This is useful for expensive calculations.
```rust, no_run
#[inline_props]
fn Calculator(cx: Scope, number: usize) -> Element {
let bigger_number = use_memo(cx, (number,), |(number,)| {
// This will only be calculated when `number` has changed.
number * 100
}):
render!(
p { "{bigger_number}" }
)
}
fn app(cx: Scope) -> Element {
render!(
Calculator { number: 0 }
)
}
```

View file

@ -11,6 +11,7 @@ Suppose we want to build a meme editor. We want to have an input to edit the mem
> Of course, in this simple example, we could write everything in one component but it is better to split everything out in smaller components to make the code more reusable, maintainable, and performant (this is even more important for larger, complex apps). > Of course, in this simple example, we could write everything in one component but it is better to split everything out in smaller components to make the code more reusable, maintainable, and performant (this is even more important for larger, complex apps).
We start with a `Meme` component, responsible for rendering a meme with a given caption: We start with a `Meme` component, responsible for rendering a meme with a given caption:
```rust ```rust
{{#include ../../../examples/meme_editor.rs:meme_component}} {{#include ../../../examples/meme_editor.rs:meme_component}}
``` ```
@ -24,12 +25,14 @@ We also create a caption editor, completely decoupled from the meme. The caption
``` ```
Finally, a third component will render the other two as children. It will be responsible for keeping the state and passing down the relevant props. Finally, a third component will render the other two as children. It will be responsible for keeping the state and passing down the relevant props.
```rust ```rust
{{#include ../../../examples/meme_editor.rs:meme_editor}} {{#include ../../../examples/meme_editor.rs:meme_editor}}
``` ```
![Meme Editor Screenshot: An old plastic skeleton sitting on a park bench. Caption: "me waiting for a language feature"](./images/meme_editor_screenshot.png) ![Meme Editor Screenshot: An old plastic skeleton sitting on a park bench. Caption: "me waiting for a language feature"](./images/meme_editor_screenshot.png)
## Using Context ## Using Shared State
Sometimes, some state needs to be shared between multiple components far down the tree, and passing it down through props is very inconvenient. Sometimes, some state needs to be shared between multiple components far down the tree, and passing it down through props is very inconvenient.
@ -39,7 +42,7 @@ Suppose now that we want to implement a dark mode toggle for our app. To achieve
Now, we could write another `use_state` in the top component, and pass `is_dark_mode` down to every component through props. But think about what will happen as the app grows in complexity almost every component that renders any CSS is going to need to know if dark mode is enabled or not so they'll all need the same dark mode prop. And every parent component will need to pass it down to them. Imagine how messy and verbose that would get, especially if we had components several levels deep! Now, we could write another `use_state` in the top component, and pass `is_dark_mode` down to every component through props. But think about what will happen as the app grows in complexity almost every component that renders any CSS is going to need to know if dark mode is enabled or not so they'll all need the same dark mode prop. And every parent component will need to pass it down to them. Imagine how messy and verbose that would get, especially if we had components several levels deep!
Dioxus offers a better solution than this "prop drilling" providing context. The [`use_context_provider`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context_provider.html) hook is similar to `use_ref`, but it makes it available through [`use_context`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_context.html) for all children components. Dioxus offers a better solution than this "prop drilling" providing context. The [`use_shared_state_provider`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_shared_state_provider.html) hook is similar to `use_ref`, but it makes it available through [`use_shared_state`](https://docs.rs/dioxus-hooks/latest/dioxus_hooks/fn.use_shared_state.html) for all children components.
First, we have to create a struct for our dark mode configuration: First, we have to create a struct for our dark mode configuration:
@ -48,19 +51,21 @@ First, we have to create a struct for our dark mode configuration:
``` ```
Now, in a top-level component (like `App`), we can provide the `DarkMode` context to all children components: Now, in a top-level component (like `App`), we can provide the `DarkMode` context to all children components:
```rust ```rust
{{#include ../../../examples/meme_editor_dark_mode.rs:context_provider}} {{#include ../../../examples/meme_editor_dark_mode.rs:context_provider}}
``` ```
As a result, any child component of `App` (direct or not), can access the `DarkMode` context. As a result, any child component of `App` (direct or not), can access the `DarkMode` context.
```rust ```rust
{{#include ../../../examples/meme_editor_dark_mode.rs:use_context}} {{#include ../../../examples/meme_editor_dark_mode.rs:use_context}}
``` ```
> `use_context` returns `Option<UseSharedState<DarkMode>>` here. If the context has been provided, the value is `Some(UseSharedState<DarkMode>)`, which you can call `.read` or `.write` on, similarly to `UseRef`. Otherwise, the value is `None`. > `use_shared_state` returns `Option<UseSharedState<DarkMode>>` here. If the context has been provided, the value is `Some(UseSharedState<DarkMode>)`, which you can call `.read` or `.write` on, similarly to `UseRef`. Otherwise, the value is `None`.
For example, here's how we would implement the dark mode toggle, which both reads the context (to determine what color it should render) and writes to it (to toggle dark mode): For example, here's how we would implement the dark mode toggle, which both reads the context (to determine what color it should render) and writes to it (to toggle dark mode):
```rust ```rust
{{#include ../../../examples/meme_editor_dark_mode.rs:toggle}} {{#include ../../../examples/meme_editor_dark_mode.rs:toggle}}
``` ```

54
examples/shared_state.rs Normal file
View file

@ -0,0 +1,54 @@
#![allow(non_snake_case)]
use dioxus::prelude::*;
fn main() {
dioxus_desktop::launch(App);
}
struct DarkMode(bool);
#[rustfmt::skip]
pub fn App(cx: Scope) -> Element {
use_shared_state_provider(cx, || DarkMode(false));
render!(
DarkModeToggle {},
AppBody {}
)
}
pub fn DarkModeToggle(cx: Scope) -> Element {
let dark_mode = use_shared_state::<DarkMode>(cx).unwrap();
let style = if dark_mode.read().0 {
"color:white"
} else {
""
};
cx.render(rsx!(label {
style: "{style}",
"Dark Mode",
input {
r#type: "checkbox",
oninput: move |event| {
let is_enabled = event.value == "true";
dark_mode.write().0 = is_enabled;
},
},
}))
}
fn AppBody(cx: Scope) -> Element {
let dark_mode = use_shared_state::<DarkMode>(cx).unwrap();
let is_dark_mode = dark_mode.read().0;
let answer = if is_dark_mode { "Yes" } else { "No" };
render!(
p {
"Is Dark mode enabled? {answer}"
}
)
}

View file

@ -9,17 +9,30 @@ use crate::UseFutureDep;
/// If a future is pending when the dependencies change, the previous future /// If a future is pending when the dependencies change, the previous future
/// will be allowed to continue /// will be allowed to continue
/// ///
/// - dependencies: a tuple of references to values that are PartialEq + Clone /// - dependencies: a tuple of references to values that are `PartialEq` + `Clone`
/// ///
/// ## Examples /// ## Examples
/// ///
/// ```rust, ignore /// ```rust, no_run
/// ///
/// #[inline_props] /// #[inline_props]
/// fn app(cx: Scope, name: &str) -> Element { /// fn Profile(cx: Scope, id: &str) -> Element {
/// use_effect(cx, (name,), |(name,)| async move { /// let name = use_state(cx, || "Default name");
/// set_title(name); ///
/// })) /// use_effect(cx, (id,), |(id,)| async move {
/// let user = fetch_user(id).await;
/// name.set(user.name);
/// });
///
/// render!(
/// p { "{name}" }
/// )
/// }
///
/// fn app(cx: Scope) -> Element {
/// render!(
/// Profile { id: "dioxusLabs" }
/// )
/// } /// }
/// ``` /// ```
pub fn use_effect<T, F, D>(cx: &ScopeState, dependencies: D, future: impl FnOnce(D::Out) -> F) pub fn use_effect<T, F, D>(cx: &ScopeState, dependencies: D, future: impl FnOnce(D::Out) -> F)

View file

@ -2,21 +2,31 @@ use dioxus_core::ScopeState;
use crate::UseFutureDep; use crate::UseFutureDep;
/// A hook that provides a callback that executes after the hooks have been applied /// A hook that provides a callback that executes if the dependencies change.
/// This is useful to avoid running computation-expensive calculations even when the data doesn't change.
/// ///
/// Whenever the hooks dependencies change, the callback will be re-evaluated. /// - dependencies: a tuple of references to values that are `PartialEq` + `Clone`
///
/// - dependencies: a tuple of references to values that are PartialEq + Clone
/// ///
/// ## Examples /// ## Examples
/// ///
/// ```rust, ignore /// ```rust, no_run
/// ///
/// #[inline_props] /// #[inline_props]
/// fn app(cx: Scope, name: &str) -> Element { /// fn Calculator(cx: Scope, number: usize) -> Element {
/// use_memo(cx, (name,), |(name,)| { /// let bigger_number = use_memo(cx, (number,), |(number,)| {
/// expensive_computation(name); /// // This will only be calculated when `number` has changed.
/// })) /// number * 100
/// }):
///
/// render!(
/// p { "{bigger_number}" }
/// )
/// }
///
/// fn app(cx: Scope) -> Element {
/// render!(
/// Calculator { number: 0 }
/// )
/// } /// }
/// ``` /// ```
pub fn use_memo<T, D>(cx: &ScopeState, dependencies: D, callback: impl FnOnce(D::Out) -> T) -> &T pub fn use_memo<T, D>(cx: &ScopeState, dependencies: D, callback: impl FnOnce(D::Out) -> T) -> &T