Merge branch 'master' into master

This commit is contained in:
Jonathan Kelley authored and GitHub committed 2023-07-14 15:36:28 -07:00
commit af49cb4ec6
313 files changed
+23988 -2334

No files matched your search

@@ -2,7 +2,7 @@
Yew subscriptions are used to schedule update for components into the future. The `Context` object can create subscriptions:
```rust
```rust, no_run
fn Component(cx: Component) -> DomTree {
let update = cx.schedule();
@@ -19,7 +19,7 @@ The subscription API exposes this functionality allowing hooks and state managem
some state or event occurs outside of the component. For instance, the `use_context` hook uses this to subscribe components that use a
particular context.
```rust
```rust, no_run
fn use_context<I>(cx: Scope<T>) -> I {
}
@@ -4,7 +4,7 @@ Concurrent mode provides a mechanism for building efficient asynchronous compone
To make a component asynchronous, simply change its function signature to async.
```rust
```rust, no_run
fn Example(cx: Scope) -> Vnode {
rsx!{ <div> "Hello world!" </div> }
}
@@ -12,7 +12,7 @@ fn Example(cx: Scope) -> Vnode {
becomes
```rust
```rust, no_run
async fn Example(cx: Scope) -> Vnode {
rsx!{ <div> "Hello world!" </div> }
}
@@ -20,7 +20,7 @@ async fn Example(cx: Scope) -> Vnode {
Now, logic in components can be awaited to delay updates of the component and its children. Like so:
```rust
```rust, no_run
async fn Example(cx: Scope) -> Vnode {
let name = fetch_name().await;
rsx!{ <div> "Hello {name}" </div> }
@@ -39,7 +39,7 @@ Instead, we suggest using hooks and future combinators that can safely utilize t
As part of our Dioxus hooks crate, we provide a data loader hook which pauses a component until its async dependencies are ready. This caches requests, reruns the fetch if dependencies have changed, and provides the option to render something else while the component is loading.
```rust
```rust, no_run
async fn ExampleLoader(cx: Scope) -> Vnode {
/*
Fetch, pause the component from rendering at all.
@@ -61,7 +61,7 @@ async fn ExampleLoader(cx: Scope) -> Vnode {
}
```
```rust
```rust, no_run
async fn Example(cx: Scope) -> DomTree {
// Diff this set between the last set
// Check if we have any outstanding tasks?
@@ -10,7 +10,7 @@ https://dmitripavlutin.com/use-react-memo-wisely/
This behavior is defined as an attribute implicit to user components. When in React land you might wrap a component with `react.memo`, Dioxus components are automatically memoized via an implicit attribute. You can manually configure this behavior on any component with "nomemo" to disable memoization.
```rust
```rust, no_run
fn test() -> DomTree {
html! {
<>
@@ -42,7 +42,7 @@ fn test_component(cx: Scope, name: String) -> Element {
Take a component like this:
```rust
```rust, no_run
fn test(cx: Scope) -> DomTree {
let Bundle { alpha, beta, gamma } = use_context::<SomeContext>(cx);
html! {
@@ -10,7 +10,7 @@ By default, Dioxus will only try to diff subtrees of components with dynamic con
Your component today might look something like this:
```rust
```rust, no_run
fn Comp(cx: Scope) -> DomTree {
let (title, set_title) = use_state(cx, || "Title".to_string());
cx.render(rsx!{
@@ -24,7 +24,7 @@ fn Comp(cx: Scope) -> DomTree {
This component is fairly straightforward – the input updates its own value on every change. However, every call to set_title will re-render the component. If we add a large list, then every time we update the title input, Dioxus will need to diff the entire list, over, and over, and over. This is **a lot** of wasted clock-cycles!
```rust
```rust, no_run
fn Comp(cx: Scope) -> DomTree {
let (title, set_title) = use_state(cx, || "Title".to_string());
cx.render(rsx!{
@@ -47,7 +47,7 @@ Many experienced React developers will just say "this is bad design" – but we
We can use signals to generate a two-way binding between data and the input box. Our text input is now just a two-line component!
```rust
```rust, no_run
fn Comp(cx: Scope) -> DomTree {
let mut title = use_signal(cx, || String::from("Title"));
cx.render(rsx!(input { value: title }))
@@ -56,7 +56,7 @@ fn Comp(cx: Scope) -> DomTree {
For a slightly more interesting example, this component calculates the sum between two numbers, but totally skips the diffing process.
```rust
```rust, no_run
fn Calculator(cx: Scope) -> DomTree {
let mut a = use_signal(cx, || 0);
let mut b = use_signal(cx, || 0);
@@ -71,7 +71,7 @@ fn Calculator(cx: Scope) -> DomTree {
Do you notice how we can use built-in operations on signals? Under the hood, we actually create a new derived signal that depends on `a` and `b`. Whenever `a` or `b` update, then `c` will update. If we need to create a new derived signal that's more complex than a basic operation (`std::ops`) we can either chain signals together or combine them:
```rust
```rust, no_run
let mut a = use_signal(cx, || 0);
let mut b = use_signal(cx, || 0);
@@ -83,7 +83,7 @@ let c = a.with(b).map(|(a, b)| *a + *b);
If we ever need to get the value out of a signal, we can simply `deref` it.
```rust
```rust, no_run
let mut a = use_signal(cx, || 0);
let c = *a + *b;
```
@@ -94,8 +94,10 @@ Calling `deref` or `deref_mut` is actually more complex than it seems. When a va
Sometimes you want a signal to propagate across your app, either through far-away siblings or through deeply-nested components. In these cases, we use Dirac: Dioxus's first-class state management toolkit. Dirac atoms automatically implement the Signal API. This component will bind the input element to the `TITLE` atom.
```rust
```rust, no_run
const TITLE: Atom<String> = Atom(|| "".to_string());
const Provider: Component = |cx|{
let title = use_signal(cx, &TITLE);
render!(input { value: title })
@@ -104,7 +106,7 @@ const Provider: Component = |cx|{
If we use the `TITLE` atom in another component, we can cause updates to flow between components without calling render or diffing either component trees:
```rust
```rust, no_run
const Receiver: Component = |cx|{
let title = use_signal(cx, &TITLE);
log::info!("This will only be called once!");
@@ -130,8 +132,9 @@ By default, Dioxus is limited when you use iter/map. With the `For` component, y
Dioxus automatically understands how to use your signals when mixed with iterators through `Deref`/`DerefMut`. This lets you efficiently map collections while avoiding the re-rendering of lists. In essence, signals act as a hint to Dioxus on how to avoid un-necessary checks and renders, making your app faster.
```rust
```rust, no_run
const DICT: AtomFamily<String, String> = AtomFamily(|_| {});
const List: Component = |cx|{
let dict = use_signal(cx, &DICT);
cx.render(rsx!(
@@ -142,14 +145,6 @@ const List: Component = |cx|{
};
```
## Remote Signals
Apps that use signals will enjoy a pleasant hybrid of server-side and client-side rendering.
```rust
```
## How does it work?
Signals internally use Dioxus' asynchronous rendering infrastructure to perform updates out of the tree.
@@ -22,13 +22,11 @@ The desktop renderer comes pre-loaded with the window and notification subtree p
Subtrees also solve the "bridging" issues in React where two different renderers need two different VirtualDoms to work properly. In Dioxus, you only ever need one VirtualDom and the right renderer plugins.
## API
Due to their importance in the hierarchy, Components – not nodes – are treated as subtree roots.
```rust
```rust, no_run
fn Subtree<P>(cx: Scope<P>) -> DomTree {
@@ -22,7 +22,7 @@ For reference, check out the WebSys renderer as a starting point for your custom
The current `RealDom` trait lives in `dioxus-core/diff`. A version of it is provided here (but might not be up-to-date):
```rust
```rust, no_run
pub trait RealDom<'a> {
fn handle_edit(&mut self, edit: DomEdit);
fn request_available_node(&mut self) -> ElementId;
@@ -32,7 +32,7 @@ pub trait RealDom<'a> {
For reference, the "DomEdit" type is a serialized enum that represents an atomic operation occurring on the RealDom. The variants roughly follow this set:
```rust
```rust, no_run
enum DomEdit {
PushRoot,
AppendChildren,
@@ -51,12 +51,11 @@ enum DomEdit {
The Dioxus diffing mechanism operates as a [stack machine](https://en.wikipedia.org/wiki/Stack_machine) where the "push_root" method pushes a new "real" DOM node onto the stack and "append_child" and "replace_with" both remove nodes from the stack.
### An example
For the sake of understanding, lets consider this example – a very simple UI declaration:
```rust
```rust, no_run
rsx!( h1 {"hello world"} )
```
@@ -64,7 +63,7 @@ To get things started, Dioxus must first navigate to the container of this h1 ta
When the renderer receives this instruction, it pushes the actual Node onto its own stack. The real renderer's stack will look like this:
```rust
```rust, no_run
instructions: [
PushRoot(Container)
]
@@ -75,7 +74,7 @@ stack: [
Next, Dioxus will encounter the h1 node. The diff algorithm decides that this node needs to be created, so Dioxus will generate the DomEdit `CreateElement`. When the renderer receives this instruction, it will create an unmounted node and push into its own stack:
```rust
```rust, no_run
instructions: [
PushRoot(Container),
CreateElement(h1),
@@ -85,8 +84,10 @@ stack: [
h1,
]
```
Next, Dioxus sees the text node, and generates the `CreateTextNode` DomEdit:
```rust
```rust, no_run
instructions: [
PushRoot(Container),
CreateElement(h1),
@@ -98,9 +99,10 @@ stack: [
"hello world"
]
```
Remember, the text node is not attached to anything (it is unmounted) so Dioxus needs to generate an Edit that connects the text node to the h1 element. It depends on the situation, but in this case we use `AppendChildren`. This pops the text node off the stack, leaving the h1 element as the next element in line.
```rust
```rust, no_run
instructions: [
PushRoot(Container),
CreateElement(h1),
@@ -112,8 +114,10 @@ stack: [
h1
]
```
We call `AppendChildren` again, popping off the h1 node and attaching it to the parent:
```rust
```rust, no_run
instructions: [
PushRoot(Container),
CreateElement(h1),
@@ -125,8 +129,10 @@ stack: [
ContainerNode,
]
```
Finally, the container is popped since we don't need it anymore.
```rust
```rust, no_run
instructions: [
PushRoot(Container),
CreateElement(h1),
@@ -137,8 +143,10 @@ instructions: [
]
stack: []
```
Over time, our stack looked like this:
```rust
```rust, no_run
[]
[Container]
[Container, h1]
@@ -164,7 +172,7 @@ Like most GUIs, Dioxus relies on an event loop to progress the VirtualDOM. The V
The code for the WebSys implementation is straightforward, so we'll add it here to demonstrate how simple an event loop is:
```rust
```rust, no_run
pub async fn run(&mut self) -> dioxus_core::error::Result<()> {
// Push the body element onto the WebsysDom's stack machine
let mut websys_dom = crate::new::WebsysDom::new(prepare_websys_dom());
@@ -194,7 +202,7 @@ pub async fn run(&mut self) -> dioxus_core::error::Result<()> {
It's important that you decode the real events from your event system into Dioxus' synthetic event system (synthetic meaning abstracted). This simply means matching your event type and creating a Dioxus `VirtualEvent` type. Your custom event must implement the corresponding event trait. Right now, the VirtualEvent system is modeled almost entirely around the HTML spec, but we are interested in slimming it down.
```rust
```rust, no_run
fn virtual_event_from_websys_event(event: &web_sys::Event) -> VirtualEvent {
match event.type_().as_str() {
"keydown" | "keypress" | "keyup" => {
@@ -224,7 +232,7 @@ These custom elements are defined as unit structs with trait implementations.
For example, the `div` element is (approximately!) defined as such:
```rust
```rust, no_run
struct div;
impl div {
/// Some glorious documentation about the class property.
@@ -235,8 +243,8 @@ impl div {
// more attributes
}
```
You've probably noticed that many elements in the `rsx!` and `html!` macros support on-hover documentation. The approach we take to custom elements means that the unit struct is created immediately where the element is used in the macro. When the macro is expanded, the doc comments still apply to the unit struct, giving tons of in-editor feedback, even inside a proc macro.
You've probably noticed that many elements in the `rsx!` and `html!` macros support on-hover documentation. The approach we take to custom elements means that the unit struct is created immediately where the element is used in the macro. When the macro is expanded, the doc comments still apply to the unit struct, giving tons of in-editor feedback, even inside a proc macro.
## Compatibility
@@ -252,7 +260,7 @@ The best hooks will properly detect the target platform and still provide functi
This particular code _will panic_ due to the unwrap on downcast_ref. Try to avoid these types of patterns.
```rust
```rust, no_run
let div_ref = use_node_ref(cx);
cx.render(rsx!{
@@ -5,11 +5,14 @@ Many modern frameworks provide a domain-specific-language for declaring user-int
With Dioxus, we actually ship two different macros – a macro that mimics JSX (the `html!` macro) and a macro that mimics Rust's native nested-struct syntax (the `rsx!` macro). These macros simply transform their inputs into NodeFactory calls.
For instance, this html! call:
```rust
```rust, no_run
html!(<div> "hello world" </div>)
```
becomes this NodeFactory call:
```rust
```rust, no_run
|f| f.element(
dioxus_elements::div, // tag
[], // listeners
@@ -18,6 +21,7 @@ becomes this NodeFactory call:
None // key
)
```
The NodeFactory API is fairly ergonomic, making it a viable option to use directly. The NodeFactory API is also compile-time correct and has incredible syntax highlighting support. We use what Rust calls a "unit type" – the `dioxus_elements::div` and associated methods to ensure that a `div` can only have attributes associated with `div`s. This lets us tack on relevant documentation, autocomplete support, and jump-to-definition for methods and attributes.
![Compile time correct syntax](../images/compiletimecorrect.png)
@@ -28,7 +32,7 @@ The html! macro supports a limited subset of the html standard. Rust's macro par
However, writing HTML by hand is a bit tedious – IDE tools for Rust don't support linting/autocomplete/syntax highlighting. We suggest using RSX – it's more natural for Rust programs and _does_ integrate well with Rust IDE tools.
```rust
```rust, no_run
let name = "jane";
let pending = false;
let count = 10;
@@ -50,7 +54,7 @@ When helpful, the Dioxus VSCode extension provides a way of converting a selecti
It's also a bit easier on the eyes than HTML.
```rust
```rust, no_run
dioxus::ssr::render_lazy(rsx! {
div {
p {"Hello, {name}!"}
@@ -2,7 +2,7 @@
To test your Rust code, you can annotate any function with the `#[test]` block. In VSCode with RA, this will provide a lens to click and run the test.
```rust
```rust, no_run
#[test]
fn component_runs() {
assert!(true)
@@ -11,7 +11,7 @@ fn component_runs() {
This will test your Rust code _without_ going through the browser. This is ideal for squashing logic bugs and ensuring components render appropriately when the browsers's DOM is not needed. If you need to run tests in the browser, you can annotate your blocks with the `#[dioxus::test]` block.
```rust
```rust, no_run
#[dioxus::test]
fn runs_in_browser() {
// ...
@@ -1,6 +1,6 @@
In the cases where you need to pass arbitrary element properties into a component – say to add more functionality to the `<a>` tag, Dioxus will accept any quoted fields. This is similar to adding arbitrary fields to regular elements using quotes.
```rust
```rust, no_run
rsx!(
Clickable {
@@ -13,7 +13,7 @@ rsx!(
For a component to accept these attributes, you must add an `attributes` field to your component's properties. We can use the spread syntax to add these attributes to whatever nodes are in our component.
```rust
```rust, no_run
#[derive(Props)]
struct ClickableProps<'a> {
attributes: Attributes<'a>
@@ -26,4 +26,5 @@ fn clickable(cx: Scope<ClickableProps<'a>>) -> Element {
"Any link, anywhere"
}
))
}
}
```
+16 -15
View File
@@ -1,6 +1,6 @@
# Thinking in Reactively
We've finally reached the point in our tutorial where we can talk about the theory of Reactivity. We've talked about defining a declarative view, but not about the aspects that make our code *reactive*.
We've finally reached the point in our tutorial where we can talk about the theory of Reactivity. We've talked about defining a declarative view, but not about the aspects that make our code _reactive_.
Understanding the theory of reactive programming is essential to making sense of Dioxus and writing effective, performant UIs.
@@ -15,7 +15,7 @@ This section is a bit long, but worth the read. We recommend coffee, tea, and/or
## Reactive Programming
Dioxus is one of a handful of Rust libraries that provide a "Reactive Programming Model". The term "Reactive programming" is a classification of programming paradigm – much like functional or imperative programming. This is a very important distinction since it affects how we *think* about our code.
Dioxus is one of a handful of Rust libraries that provide a "Reactive Programming Model". The term "Reactive programming" is a classification of programming paradigm – much like functional or imperative programming. This is a very important distinction since it affects how we _think_ about our code.
Reactive programming is a programming model concerned with deriving computations from asynchronous data flow. Most reactive programs are comprised of datasources, intermediate computations, and a final result.
@@ -33,7 +33,7 @@ In Reactive Programming, we don't think about whether or not we should reevaluat
In Rust, our reactive app would look something like:
```rust
```rust, no_run
fn compute_g(t: i32, seconds: i32) -> bool {
t > seconds
}
@@ -55,7 +55,7 @@ The Dioxus VirtualDom provides us a framework for reactive programming. When we
If we represented the reactive graph presented above in Dioxus, it would look very similar:
```rust
```rust, no_run
// Declare a component that holds our datasources and calculates `g`
fn RenderGraph(cx: Scope) -> Element {
let seconds = use_datasource(SECONDS);
@@ -83,11 +83,11 @@ fn RenderT(cx: Scope, seconds: i32, constant: i32) -> Element {
With this app, we've defined three components. Our top-level component provides our datasources (the hooks), computation nodes (child components), and a final value (what's "rendered").
Now, whenever the `constant` changes, our `RenderT` component will be re-rendered. However, if `seconds` doesn't change, then we don't need to re-render `RenderG` because the input is the same. If `seconds` *does* change, then both RenderG and RenderT will be reevaluated.
Now, whenever the `constant` changes, our `RenderT` component will be re-rendered. However, if `seconds` doesn't change, then we don't need to re-render `RenderG` because the input is the same. If `seconds` _does_ change, then both RenderG and RenderT will be reevaluated.
Dioxus is "Reactive" because it provides this framework for us. All we need to do is write our own tiny units of computation and Dioxus figures out which components need to be reevaluated automatically.
These extra checks and algorithms add some overhead, which is why you see projects like [Sycamore](http://sycamore-rs.netlify.app) and [SolidJS](http://solidjs.com) eliminating them altogether. Dioxus is *really* fast, so we're willing to exchange the added overhead for improved developer experience.
These extra checks and algorithms add some overhead, which is why you see projects like [Sycamore](http://sycamore-rs.netlify.app) and [SolidJS](http://solidjs.com) eliminating them altogether. Dioxus is _really_ fast, so we're willing to exchange the added overhead for improved developer experience.
## How do we update values in our dataflow graph?
@@ -104,7 +104,7 @@ Technically, the root props of the VirtualDom are a third datasource, but since
For local state in hooks, Dioxus gives us the `use_hook` method which returns an `&mut T` without any requirements. This means raw hook values are not tracked by Dioxus. In fact, we could write a component that modifies a hook value directly:
```rust
```rust, no_run
fn app(cx: Scope) -> Element {
let mut count = cx.use_hook(|_| 0);
cx.render(rsx!{
@@ -118,7 +118,7 @@ fn app(cx: Scope) -> Element {
However, when this value is written to, the component does not know to be reevaluated. We must explicitly tell Dioxus that this component is "dirty" and needs to be re-rendered. This is done through the `cx.needs_update` method:
```rust
```rust, no_run
button {
onclick: move |_| {
*count += 1;
@@ -130,7 +130,7 @@ button {
Now, whenever we click the button, the value will change and the component will be re-rendered.
> Re-rendering is when Dioxus calls your function component *again*. Component functions will be called over and over throughout their lifetime, so they should be mostly side-effect free.
> Re-rendering is when Dioxus calls your function component _again_. Component functions will be called over and over throughout their lifetime, so they should be mostly side-effect free.
### Understand this!
@@ -146,9 +146,9 @@ To make app-global state easier to reason about, Dioxus makes all values provide
In these cases, App-Global state needs to manually track which components need to be re-generated.
To regenerate *any* component in your app, you can get a handle to the Dioxus' internal scheduler through `schedule_update_any`:
To regenerate _any_ component in your app, you can get a handle to the Dioxus' internal scheduler through `schedule_update_any`:
```rust
```rust, no_run
let force_render = cx.schedule_update_any();
// force a render of the root component
@@ -179,9 +179,9 @@ From here, Dioxus computes the difference between these trees and updates the Re
## Suppressing Renders
So, we know how to make Dioxus render, but how do we *stop* it? What if we *know* that our state didn't change and we shouldn't render and diff new nodes because they'll be exactly the same as the last time?
So, we know how to make Dioxus render, but how do we _stop_ it? What if we _know_ that our state didn't change and we shouldn't render and diff new nodes because they'll be exactly the same as the last time?
In these cases, you want to reach for *memoization*. In Dioxus, memoization involves preventing a component from rendering again if its props didn't change since the last time it attempted to render.
In these cases, you want to reach for _memoization_. In Dioxus, memoization involves preventing a component from rendering again if its props didn't change since the last time it attempted to render.
Visually, you can tell that a component will only re-render if the new value is sufficiently different than the old one.
@@ -196,7 +196,7 @@ Visually, you can tell that a component will only re-render if the new value is
This is why when you `derive(Props)`, you must also implement the `PartialEq` trait. To override the memoization strategy for a component, you can simply implement your own PartialEq.
```rust
```rust, no_run
struct CustomProps {
val: i32,
}
@@ -215,7 +215,7 @@ However, for components that borrow data, it doesn't make sense to implement Par
You can technically override this behavior by implementing the `Props` trait manually, though it's unsafe and easy to mess up:
```rust
```rust, no_run
unsafe impl Properties for CustomProps {
fn memoize(&self, other &Self) -> bool {
self != other
@@ -224,6 +224,7 @@ unsafe impl Properties for CustomProps {
```
TLDR:
- Dioxus checks if props changed between renders
- If props changed according to PartialEq, Dioxus re-renders the component
- Props that have a lifetime (ie `<'a>`) will always be re-rendered
+3 -3
View File
@@ -6,7 +6,7 @@ One of the most reliable state management patterns in large Dioxus apps is `fan-
With `fan-out`, our individual components at "leaf" position of our VirtualDom are "pure", making them easily reusable, testable, and deterministic. For instance, the "title" bar of our app might be a fairly complicated component.
```rust
```rust, no_run
#[derive(Props, PartialEq)]
struct TitlebarProps {
title: String,
@@ -26,7 +26,7 @@ fn Titlebar(cx: Scope<TitlebarProps>) -> Element {
If we used global state like use_context or fermi, we might be tempted to inject our `use_read` directly into the component.
```rust
```rust, no_run
fn Titlebar(cx: Scope<TitlebarProps>) -> Element {
let title = use_read(cx, TITLE);
let subtitle = use_read(cx, SUBTITLE);
@@ -41,7 +41,7 @@ For many apps – this is a fine pattern, especially if the component is a one-o
To enable our titlebar component to be used across apps, we want to lift our atoms upwards and out of the Titlebar component. We would organize a bunch of other components in this section of the app to share some of the same state.
```rust
```rust, no_run
fn DocsiteTitlesection(cx: Scope) {
let title = use_read(cx, TITLE);
let subtitle = use_read(cx, SUBTITLE);
+3 -5
View File
@@ -4,16 +4,15 @@ Every app you'll build with Dioxus will have some sort of state that needs to be
In this chapter, we'll cover the various ways to manage state, the appropriate terminology, various patterns, and some problems you might run into.
## The Problem
Why do people say state management is so difficult? What does it mean?
Generally, state management is the code you need to write to ensure that your app renders the *correct* content. If the user inputs a name, then you need to display the appropriate response – like alerts, validation, and disable/enable various elements on the page. Things can quickly become tricky if you need loading screens and cancellable tasks.
Generally, state management is the code you need to write to ensure that your app renders the _correct_ content. If the user inputs a name, then you need to display the appropriate response – like alerts, validation, and disable/enable various elements on the page. Things can quickly become tricky if you need loading screens and cancellable tasks.
For the simplest of apps, all of your state can enter the app from the root props. This is common in server-side rendering – we can collect all of the required state *before* rendering the content.
For the simplest of apps, all of your state can enter the app from the root props. This is common in server-side rendering – we can collect all of the required state _before_ rendering the content.
```rust
```rust, no_run
let all_content = get_all_content().await;
let output = dioxus::ssr::render_lazy(rsx!{
@@ -27,7 +26,6 @@ With this incredibly simple setup, it is highly unlikely that you'll have render
However, most of your apps will store state inside of the Dioxus VirtualDom – either through local state or global state.
## Your options
To deal with complexity, you have a couple of options:
+10 -13
View File
@@ -6,7 +6,7 @@ The first step to dealing with complexity in your app is to refactor your state
Let's say we're managing the state for a list of Todos. Whenever we edit the todo, we want the list to update. We might've started building our app but putting everything into a single `use_ref`.
```rust
```rust, no_run
struct Todo {
contents: String,
is_hovered: bool,
@@ -29,7 +29,7 @@ cx.render(rsx!{
As shown above, whenever the todo is hovered, we want to set its state:
```rust
```rust, no_run
todos.write()[0].is_hovered = true;
```
@@ -37,7 +37,7 @@ As the amount of interactions goes up, so does the complexity of our state. Shou
Instead, let's refactor our Todo component to handle its own state:
```rust
```rust, no_run
#[inline_props]
fn Todo<'a>(cx: Scope, todo: &'a Todo) -> Element {
let is_hovered = use_state(cx, || false);
@@ -53,16 +53,15 @@ fn Todo<'a>(cx: Scope, todo: &'a Todo) -> Element {
Now, we can simplify our Todo data model to get rid of local UI state:
```rust
```rust, no_run
struct Todo {
contents: String,
}
```
This is not only better for encapsulation and abstraction, but it's only more performant! Whenever a Todo is hovered, we won't need to re-render *every* Todo again – only the Todo that's currently being hovered.
This is not only better for encapsulation and abstraction, but it's only more performant! Whenever a Todo is hovered, we won't need to re-render _every_ Todo again – only the Todo that's currently being hovered.
Wherever possible, you should try to refactor the "view" layer *out* of your data model.
Wherever possible, you should try to refactor the "view" layer _out_ of your data model.
## Immutability
@@ -72,7 +71,7 @@ In these scenarios consider breaking your `use_ref` into individual `use_state`s
You might've started modeling your component with a struct and use_ref
```rust
```rust, no_run
struct State {
count: i32,
color: &'static str,
@@ -85,17 +84,17 @@ let state = use_ref(cx, State::new)
The "better" approach for this particular component would be to break the state apart into different values:
```rust
```rust, no_run
let count = use_state(cx, || 0);
let color = use_state(cx, || "red");
let names = use_state(cx, HashMap::new);
```
You might recognize that our "names" value is a HashMap – which is not terribly cheap to clone every time we update its value. To solve this issue, we *highly* suggest using a library like [`im`](https://crates.io/crates/im) which will take advantage of structural sharing to make clones and mutations much cheaper.
You might recognize that our "names" value is a HashMap – which is not terribly cheap to clone every time we update its value. To solve this issue, we _highly_ suggest using a library like [`im`](https://crates.io/crates/im) which will take advantage of structural sharing to make clones and mutations much cheaper.
When combined with the `make_mut` method on `use_state`, you can get really succinct updates to collections:
```rust
```rust, no_run
let todos = use_state(cx, im_rc::HashMap::default);
todos.make_mut().insert("new todo", Todo {
@@ -106,5 +105,3 @@ todos.make_mut().insert("new todo", Todo {
## Moving on
This particular local patterns are powerful but is not a cure-all for state management problems. Sometimes your state problems are much larger than just staying local to a component.
+1 -3
View File
@@ -1,11 +1,10 @@
## Memoization
Dioxus uses Memoization for a more efficient user interface. Memoization is the process in which we check if a component actually needs to be re-rendered when its props change. If a component's properties change but they wouldn't affect the output, then we don't need to re-render the component, saving time!
For example, let's say we have a component that has two children:
```rust
```rust, no_run
fn Demo(cx: Scope) -> Element {
// don't worry about these 2, we'll cover them later
let name = use_state(cx, || String::from("bob"));
@@ -25,4 +24,3 @@ Dioxus memoizes owned components. It uses `PartialEq` to determine if a componen
> This means you can always rely on props with `PartialEq` or no props at all to act as barriers in your app. This can be extremely useful when building larger apps where properties frequently change. By moving our state into a global state management solution, we can achieve precise, surgical re-renders, improving the performance of our app.
Borrowed Props cannot be safely memoized. However, this is not a problem – Dioxus relies on the memoization of their parents to determine if they need to be rerendered.
+4 -7
View File
@@ -1,12 +1,10 @@
## Using UseRef with "models"
One option for state management that UseRef enables is the development of a "model" for your components. This particular pattern enables you to model your state with regular structs.
For instance, our calculator example uses a struct to model the state.
```rust
```rust, no_run
struct Calculator {
display_value: String,
@@ -18,7 +16,7 @@ struct Calculator {
Our component is really simple – we just call `use_ref` to get an initial calculator state.
```rust
```rust, no_run
fn app(cx: Scope) -> Element {
let state = use_ref(cx, Calculator::new);
@@ -30,7 +28,7 @@ fn app(cx: Scope) -> Element {
In our UI, we can then use `read` and a helper method to get data out of the model.
```rust
```rust, no_run
// Our accessor method
impl Calculator {
fn formatted_display(&self) -> String {
@@ -49,7 +47,7 @@ cx.render(rsx!{
To modify the state, we can setup a helper method and then attach it to a callback.
```rust
```rust, no_run
// our helper
impl Calculator {
fn clear_display(&mut self) {
@@ -64,4 +62,3 @@ cx.render(rsx!{
}
})
```