Internationalization: move guide to en folder and preserve its history. (#494)

* chore: move guide to en folder

* docs: add english as language
This commit is contained in:
Jon Kelley authored and GitHub committed 2022-07-09 12:31:46 -04:00
1 parent 7fdc72726d
commit c97ca7dff6
69 files changed
+4 -1

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
This directory includes:
- Very outdated docs
- Docs for features which haven't been implemented (yet?)
- Information which has already been covered in the guide in a more organized fashion
- A few things yet to be integrated into the guide nicely
@@ -0,0 +1,33 @@
# Subscriptions
Yew subscriptions are used to schedule update for components into the future. The `Context` object can create subscriptions:
```rust
fn Component(cx: Component) -> DomTree {
let update = cx.schedule();
// Now, when the subscription is called, the component will be re-evaluated
update.consume();
}
```
Whenever a component's subscription is called, the component will then re-evaluated. You can consider the input properties of
a component to be just another form of subscription. By default, the Dioxus component system automatically diffs a component's props
when the parent function is called, and if the props are different, the child component's subscription is called.
The subscription API exposes this functionality allowing hooks and state management solutions the ability to update components whenever
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
fn use_context<I>(cx: Scope<T>) -> I {
}
```
@@ -0,0 +1,82 @@
# Concurrent mode
Concurrent mode provides a mechanism for building efficient asynchronous components. With this feature, components don't need to render immediately, and instead can schedule a future render by returning a future.
To make a component asynchronous, simply change its function signature to async.
```rust
fn Example(cx: Scope) -> Vnode {
rsx!{ <div> "Hello world!" </div> }
}
```
becomes
```rust
async fn Example(cx: Scope) -> Vnode {
rsx!{ <div> "Hello world!" </div> }
}
```
Now, logic in components can be awaited to delay updates of the component and its children. Like so:
```rust
async fn Example(cx: Scope) -> Vnode {
let name = fetch_name().await;
rsx!{ <div> "Hello {name}" </div> }
}
async fetch_name() -> String {
// ...
}
```
This component will only schedule its render once the fetch is complete. However, we _don't_ recommend using async/await directly in your components.
Async is a notoriously challenging yet rewarding tool for efficient tools. If not careful, locking and unlocking shared aspects of the component's context can lead to data races and panics. If a shared resource is locked while the component is awaiting, then other components can be locked or panic when trying to access the same resource. These rules are especially important when references to shared global state are accessed using the context object's lifetime. If mutable references to data captured immutably by the context are taken, then the component will panic, causing confusion.
Instead, we suggest using hooks and future combinators that can safely utilize the safeguards of the component's Context when interacting with async tasks.
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
async fn ExampleLoader(cx: Scope) -> Vnode {
/*
Fetch, pause the component from rendering at all.
The component is locked while waiting for the request to complete
While waiting, an alternate component is scheduled in its place.
This API stores the result on the Context object, so the loaded data is taken as reference.
*/
let name: &Result<SomeStructure> = use_fetch_data("http://example.com/json", ())
.place_holder(|cx| rsx!{<div> "loading..." </div>})
.delayed_place_holder(1000, |cx| rsx!{ <div> "still loading..." </div>})
.await;
match name {
Ok(name) => rsx! { <div> "Hello {something}" </div> },
Err(e) => rsx! { <div> "An error occurred :(" </div>}
}
}
```
```rust
async fn Example(cx: Scope) -> DomTree {
// Diff this set between the last set
// Check if we have any outstanding tasks?
//
// Eventually, render the component into the VDOM when the future completes
<div>
<Example />
</div>
// Render a div, queue a component
// Render the placeholder first, then when the component is ready, then render the component
<div>
<Suspense placeholder={html!{<div>"Loading"</div>}}>
<Example />
</Suspense>
</div>
}
```
@@ -0,0 +1,58 @@
# Memoization and the arena allocator
Dioxus differs slightly from other UI virtual doms in some subtle ways due to its memory allocator.
One important aspect to understand is how props are passed down from parent components to children. All "components" (custom user-made UI elements) are tightly allocated together in an arena. However, because props and hooks are generically typed, they are casted to `Any` and allocated on the heap – not in the arena with the components.
With this system, we try to be more efficient when leaving the component arena and entering the heap. By default, props are memoized between renders using COW and context. This makes props comparisons fast – done via ptr comparisons on the cow pointer. Because memoization is done by default, parent re-renders will _not_ cascade to children if the child's props did not change.
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
fn test() -> DomTree {
html! {
<>
<SomeComponent nomemo />
// same as
<SomeComponent nomemo=true />
</>
}
}
static TestComponent: Component = |cx| html!{<div>"Hello world"</div>};
static TestComponent: Component = |cx|{
let g = "BLAH";
html! {
<div> "Hello world" </div>
}
};
#[inline_props]
fn test_component(cx: Scope, name: String) -> Element {
rsx!(cx, "Hello, {name}")
}
```
## Why this behavior?
"This is different than React, why differ?".
Take a component like this:
```rust
fn test(cx: Scope) -> DomTree {
let Bundle { alpha, beta, gamma } = use_context::<SomeContext>(cx);
html! {
<div>
<Component name=alpha />
<Component name=beta />
<Component name=gamma />
</div>
}
}
```
While the contents of the destructured bundle might change, not every child component will need to be re-rendered every time the context changes.
@@ -0,0 +1,155 @@
# Signals: Skipping the Diff
In most cases, the traditional VirtualDOM diffing pattern is plenty fast. Dioxus will compare trees of VNodes, find the differences, and then update the Renderer's DOM with the diffs. However, this can generate a lot of overhead for certain types of components. In apps where reducing visual latency is a top priority, you can opt into the `Signals` api to entirely disable diffing of hot-path components. Dioxus will then automatically construct a state machine for your component, making updates nearly instant.
Signals build on the same infrastructure that powers asynchronous rendering where in-tree values can be updated outside of the render phase. In async rendering, a future is used as the signal source. With the raw signal API, any value can be used as a signal source.
By default, Dioxus will only try to diff subtrees of components with dynamic content, automatically skipping diffing static content.
## What does this look like?
Your component today might look something like this:
```rust
fn Comp(cx: Scope) -> DomTree {
let (title, set_title) = use_state(&cx, || "Title".to_string());
cx.render(rsx!{
input {
value: title,
onchange: move |new| set_title(new.value())
}
})
}
```
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
fn Comp(cx: Scope) -> DomTree {
let (title, set_title) = use_state(&cx, || "Title".to_string());
cx.render(rsx!{
div {
input {
value: title,
onchange: move |new| set_title(new.value())
}
ul {
{0..10000.map(|f| rsx!{
li { "{f}" }
})}
}
}
})
}
```
Many experienced React developers will just say "this is bad design" – but we consider it to be a pit of failure, rather than a pit of success! That's why signals exist – to push you in a more performant (and ergonomic) direction. Signals let us directly bind values to their final place in the VirtualDOM. Whenever the signal value is updated, Dioxus will only the DOM nodes where that signal is used. Signals are built into Dioxus, so we can directly bind attributes of elements to their updates.
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
fn Comp(cx: Scope) -> DomTree {
let mut title = use_signal(&cx, || String::from("Title"));
cx.render(rsx!(input { value: title }))
}
```
For a slightly more interesting example, this component calculates the sum between two numbers, but totally skips the diffing process.
```rust
fn Calculator(cx: Scope) -> DomTree {
let mut a = use_signal(&cx, || 0);
let mut b = use_signal(&cx, || 0);
let mut c = a + b;
rsx! {
input { value: a }
input { value: b }
p { "a + b = {c}" }
}
}
```
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
let mut a = use_signal(&cx, || 0);
let mut b = use_signal(&cx, || 0);
// Chain signals together using the `with` method
let c = a.with(b).map(|(a, b)| *a + *b);
```
## Deref and DerefMut
If we ever need to get the value out of a signal, we can simply `deref` it.
```rust
let mut a = use_signal(&cx, || 0);
let c = *a + *b;
```
Calling `deref` or `deref_mut` is actually more complex than it seems. When a value is derefed, you're essentially telling Dioxus that _this_ element _needs_ to be subscribed to the signal. If a signal is derefed outside of an element, the entire component will be subscribed and the advantage of skipping diffing will be lost. Dioxus will throw an error in the console when this happens to tell you that you're using signals wrong, but your component will continue to work.
## Global Signals
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
const TITLE: Atom<String> = || "".to_string();
const Provider: Component = |cx|{
let title = use_signal(&cx, &TITLE);
rsx!(cx, input { value: title })
};
```
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
const Receiver: Component = |cx|{
let title = use_signal(&cx, &TITLE);
log::info!("This will only be called once!");
rsx!(cx,
div {
h1 { "{title}" }
div {}
footer {}
}
)
};
```
Dioxus knows that the receiver's `title` signal is used only in the text node, and skips diffing Receiver entirely, knowing to update _just_ the text node.
If you build a complex app on top of Dirac, you'll likely notice that many of your components simply won't be diffed at all. For instance, our Receiver component will never be diffed once it has been mounted!
## Signals and Iterators
Sometimes you want to use a collection of items. With Signals, you can bypass diffing for collections – a very powerful technique to avoid re-rendering on large collections.
By default, Dioxus is limited when you use iter/map. With the `For` component, you can provide an iterator and a function for the iterator to map to.
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
const DICT: AtomFamily<String, String> = |_| {};
const List: Component = |cx|{
let dict = use_signal(&cx, &DICT);
cx.render(rsx!(
ul {
For { each: dict, map: |k, v| rsx!( li { "{v}" }) }
}
))
};
```
## 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.
@@ -0,0 +1,54 @@
# Subtrees
One way of extending the Dioxus VirtualDom is through the use of "Subtrees." Subtrees are chunks of the VirtualDom tree distinct from the rest of the tree. They still participate in event bubbling, diffing, etc, but will have a separate set of edits generated during the diff phase.
For a VirtualDom that has a root tree with two subtrees, the edits follow a pattern of:
Root
-> Tree 1
-> Tree 2
-> Original root tree
- Root edits
- Tree 1 Edits
- Tree 2 Edits
- Root Edits
The goal of this functionality is to enable things like Portals, Windows, and inline alternative renderers without needing to spin up a new VirtualDom.
With the right renderer plugins, a subtree could be rendered as anything – a 3D scene, SVG, or even as the contents of a new window or modal. This functionality is similar to "Portals" in React, but much more "renderer agnostic." Portals, by nature, are not necessarily cross-platform and rely on renderer functionality, so it makes sense to abstract their purpose into the subtree concept.
The desktop renderer comes pre-loaded with the window and notification subtree plugins, making it possible to render subtrees into entirely different windows.
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
fn Subtree<P>(cx: Scope<P>) -> DomTree {
}
fn Window() -> DomTree {
Subtree {
onassign: move |e| {
// create window
}
children()
}
}
fn 3dRenderer -> DomTree {
Subtree {
onassign: move |e| {
// initialize bevy
}
}
}
```
@@ -0,0 +1,272 @@
# Custom Renderer
Dioxus is an incredibly portable framework for UI development. The lessons, knowledge, hooks, and components you acquire over time can always be used for future projects. However, sometimes those projects cannot leverage a supported renderer or you need to implement your own better renderer.
Great news: the design of the renderer is entirely up to you! We provide suggestions and inspiration with the 1st party renderers, but only really require implementation of the `RealDom` trait for things to function properly.
## The specifics:
Implementing the renderer is fairly straightforward. The renderer needs to:
1. Handle the stream of edits generated by updates to the virtual DOM
2. Register listeners and pass events into the virtual DOM's event system
3. Progress the virtual DOM with an async executor (or disable the suspense API and use `progress_sync`)
Essentially, your renderer needs to implement the `RealDom` trait and generate `EventTrigger` objects to update the VirtualDOM. From there, you'll have everything needed to render the VirtualDOM to the screen.
Internally, Dioxus handles the tree relationship, diffing, memory management, and the event system, leaving as little as possible required for renderers to implement themselves.
For reference, check out the WebSys renderer as a starting point for your custom renderer.
## Trait implementation and DomEdits
The current `RealDom` trait lives in `dioxus-core/diff`. A version of it is provided here (but might not be up-to-date):
```rust
pub trait RealDom<'a> {
fn handle_edit(&mut self, edit: DomEdit);
fn request_available_node(&mut self) -> ElementId;
fn raw_node_as_any(&self) -> &mut dyn Any;
}
```
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
enum DomEdit {
PushRoot,
AppendChildren,
ReplaceWith,
CreateTextNode,
CreateElement,
CreateElementNs,
CreatePlaceholder,
NewEventListener,
RemoveEventListener,
SetText,
SetAttribute,
RemoveAttribute,
}
```
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
rsx!( h1 {"hello world"} )
```
To get things started, Dioxus must first navigate to the container of this h1 tag. To "navigate" here, the internal diffing algorithm generates the DomEdit `PushRoot` where the ID of the root is the container.
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
instructions: [
PushRoot(Container)
]
stack: [
ContainerNode,
]
```
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
instructions: [
PushRoot(Container),
CreateElement(h1),
]
stack: [
ContainerNode,
h1,
]
```
Next, Dioxus sees the text node, and generates the `CreateTextNode` DomEdit:
```rust
instructions: [
PushRoot(Container),
CreateElement(h1),
CreateTextNode("hello world")
]
stack: [
ContainerNode,
h1,
"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
instructions: [
PushRoot(Container),
CreateElement(h1),
CreateTextNode("hello world"),
AppendChildren(1)
]
stack: [
ContainerNode,
h1
]
```
We call `AppendChildren` again, popping off the h1 node and attaching it to the parent:
```rust
instructions: [
PushRoot(Container),
CreateElement(h1),
CreateTextNode("hello world"),
AppendChildren(1),
AppendChildren(1)
]
stack: [
ContainerNode,
]
```
Finally, the container is popped since we don't need it anymore.
```rust
instructions: [
PushRoot(Container),
CreateElement(h1),
CreateTextNode("hello world"),
AppendChildren(1),
AppendChildren(1),
Pop(1)
]
stack: []
```
Over time, our stack looked like this:
```rust
[]
[Container]
[Container, h1]
[Container, h1, "hello world"]
[Container, h1]
[Container]
[]
```
Notice how our stack is empty once UI has been mounted. Conveniently, this approach completely separates the VirtualDOM and the Real DOM. Additionally, these edits are serializable, meaning we can even manage UIs across a network connection. This little stack machine and serialized edits makes Dioxus independent of platform specifics.
Dioxus is also really fast. Because Dioxus splits the diff and patch phase, it's able to make all the edits to the RealDOM in a very short amount of time (less than a single frame) making rendering very snappy. It also allows Dioxus to cancel large diffing operations if higher priority work comes in while it's diffing.
It's important to note that there _is_ one layer of connectedness between Dioxus and the renderer. Dioxus saves and loads elements (the PushRoot edit) with an ID. Inside the VirtualDOM, this is just tracked as a u64.
Whenever a `CreateElement` edit is generated during diffing, Dioxus increments its node counter and assigns that new element its current NodeCount. The RealDom is responsible for remembering this ID and pushing the correct node when PushRoot(ID) is generated. Dioxus doesn't reclaim IDs of elements its removed, but your renderer probably will want to. To do this, we suggest using a `SecondarySlotMap` if implementing the renderer in Rust, or just deferring to a HashMap-type approach.
This little demo serves to show exactly how a Renderer would need to process an edit stream to build UIs. A set of serialized EditStreams for various demos is available for you to test your custom renderer against.
## Event loop
Like most GUIs, Dioxus relies on an event loop to progress the VirtualDOM. The VirtualDOM itself can produce events as well, so it's important that your custom renderer can handle those too.
The code for the WebSys implementation is straightforward, so we'll add it here to demonstrate how simple an event loop is:
```rust
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());
websys_dom.stack.push(root_node);
// Rebuild or hydrate the virtualdom
self.internal_dom.rebuild(&mut websys_dom)?;
// Wait for updates from the real dom and progress the virtual dom
loop {
let user_input_future = websys_dom.wait_for_event();
let internal_event_future = self.internal_dom.wait_for_event();
match select(user_input_future, internal_event_future).await {
Either::Left((trigger, _)) => trigger,
Either::Right((trigger, _)) => trigger,
}
}
while let Some(trigger) = {
websys_dom.stack.push(body_element.first_child().unwrap());
self.internal_dom
.progress_with_event(&mut websys_dom, trigger)?;
}
}
```
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
fn virtual_event_from_websys_event(event: &web_sys::Event) -> VirtualEvent {
match event.type_().as_str() {
"keydown" | "keypress" | "keyup" => {
struct CustomKeyboardEvent(web_sys::KeyboardEvent);
impl dioxus::events::KeyboardEvent for CustomKeyboardEvent {
fn char_code(&self) -> usize { self.0.char_code() }
fn ctrl_key(&self) -> bool { self.0.ctrl_key() }
fn key(&self) -> String { self.0.key() }
fn key_code(&self) -> usize { self.0.key_code() }
fn location(&self) -> usize { self.0.location() }
fn meta_key(&self) -> bool { self.0.meta_key() }
fn repeat(&self) -> bool { self.0.repeat() }
fn shift_key(&self) -> bool { self.0.shift_key() }
fn which(&self) -> usize { self.0.which() }
fn get_modifier_state(&self, key_code: usize) -> bool { self.0.get_modifier_state() }
}
VirtualEvent::KeyboardEvent(Rc::new(event.clone().dyn_into().unwrap()))
}
_ => todo!()
```
## Custom raw elements
If you need to go as far as relying on custom elements for your renderer – you totally can. This still enables you to use Dioxus' reactive nature, component system, shared state, and other features, but will ultimately generate different nodes. All attributes and listeners for the HTML and SVG namespace are shuttled through helper structs that essentially compile away (pose no runtime overhead). You can drop in your own elements any time you want, with little hassle. However, you must be absolutely sure your renderer can handle the new type, or it will crash and burn.
These custom elements are defined as unit structs with trait implementations.
For example, the `div` element is (approximately!) defined as such:
```rust
struct div;
impl div {
/// Some glorious documentation about the class property.
#[inline]
fn class<'a>(&self, cx: NodeFactory<'a>, val: Arguments) -> Attribute<'a> {
cx.attr("class", val, None, false)
}
// 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.
## Compatibility
Forewarning: not every hook and service will work on your platform. Dioxus wraps things that need to be cross-platform in "synthetic" types. However, downcasting to a native type might fail if the types don't match.
There are three opportunities for platform incompatibilities to break your program:
1. When downcasting elements via `Ref.downcast_ref<T>()`
2. When downcasting events via `Event.downcast_ref<T>()`
3. Calling platform-specific APIs that don't exist
The best hooks will properly detect the target platform and still provide functionality, failing gracefully when a platform is not supported. We encourage – and provide – an indication to the user on what platforms a hook supports. For issues 1 and 2, these return a result as to not cause panics on unsupported platforms. When designing your hooks, we recommend propagating this error upwards into user facing code, making it obvious that this particular service is not supported.
This particular code _will panic_ due to the unwrap on downcast_ref. Try to avoid these types of patterns.
```rust
let div_ref = use_node_ref(cx);
cx.render(rsx!{
div { ref: div_ref, class: "custom class",
button { "click me to see my parent's class"
onclick: move |_| if let Some(div_ref) = div_ref {
log::info!("Div class is {}", div_ref.downcast_ref::<web_sys::Element>().unwrap().class())
}
}
}
})
```
## Conclusion
That should be it! You should have nearly all the knowledge required on how to implement your own renderer. We're super interested in seeing Dioxus apps brought to custom desktop renderers, mobile renderer, video game UI, and even augmented reality! If you're interesting in contributing to any of the these projects, don't be afraid to reach out or join the community.
@@ -0,0 +1,32 @@
# Dioxus Liveview
Liveview is a configuration where a server and a client work together to render a Dioxus app. Liveview monomorphizes a web application, eliminating the need for frontend-specific APIs.
This is a developer-friendly alternative to the JAM-stack (Javascript + API + Markdown), combining the Wasm-compatibility and async performance of Rust.
## Why liveview?
### No APIs necessary!
Because Liveview combines the server and the client, you'll find dedicated APIs unnecessary. You'll still want to implement a data-fetching service for Live-apps, but this can be implemented as a crate and shared between apps. This approach was designed to let you model out your data requirements without needing to maintain a public versioned API.
You can find more information to data modeling and fetching for LiveApps in the "Book of Dioxus Patterns".
### Ease of deployment
There is no hassle for deploying Dioxus liveview apps – simply upload the binary to your hosting provider of choice. There simply is no need to deal with intermediate APIs. An app's frontend and backend are tightly coupled to each other, meaning that the backed and frontend are always up to date.
This is especially powerful for small teams, where fast iteration, versioned unique prototypes, and simple deployments are important. As your app grows, Dioxus will happily grow with you, serving up to 100K RPS (thanks to async Rust performance).
### Power of server rendering combined with the reactive nature of JavaScript
Liveview apps are backed by a server and enhanced with web-assembly. This completely eliminates the need to write Javascript to add dynamic content to webpages. Apps are written in only **one** language and require essentially 0 knowledge of build systems, transpiling or ECMAScript versions. Minimum browser support is guaranteed to cover 95% of users, and the Dioxus-CLI can be configured to generate polyfills for even more support.
### Support with LiveHost by Dioxus-Labs
The Dioxus-CLI comes ready for use with premium Dioxus-Labs services, like LiveHost. Simply link up your git repo to the Dioxus LiveHost and start deploying your fullstack Dioxus app today. LiveHost supports:
- Versioned fronted/backend with unique links
- Builtin CI/CD
- Managed and pluggable storage database backends
- Serverless support for minimal latency
- Site Analytics
- Lighthouse optimization
- On-premise support (see license terms)
Dioxus LiveHost is a Dioxus LiveApp management service with all supported features in a single binary. For OSS, we permit free usage and deployment of LiveHost to your favorite hosting provider.
@@ -0,0 +1,63 @@
# VNodes with RSX, HTML, and NodeFactory
Many modern frameworks provide a domain-specific-language for declaring user-interfaces. In the case of React, this language extension is called JSX and must be handled through additional dependencies and pre/post processors to transform your source code. With Rust, we can simply provide a procedural macro in the Dioxus dependency itself that mimics the JSX language.
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
html!(<div> "hello world" </div>)
```
becomes this NodeFactory call:
```rust
|f| f.element(
dioxus_elements::div, // tag
[], // listeners
[], // attributes
[f.static_text("hello world")], // children
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)
## html! macro
The html! macro supports a limited subset of the html standard. Rust's macro parsing tools are somewhat limited, so all text between tags _must be quoted_.
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
let name = "jane";
let pending = false;
let count = 10;
dioxus::ssr::render_lazy(html! {
<div>
<p> "Hello, {name}!" </p>
<p> "Status: {pending}!" </p>
<p> "Count {count}!" </p>
</div>
});
```
## rsx! macro
The rsx! macro is a VNode builder macro designed especially for Rust programs. Writing these should feel very natural, much like assembling a struct. VSCode also supports these with code folding, bracket-tabbing, bracket highlighting, section selecting, inline documentation, GOTO definition, and refactoring support.
When helpful, the Dioxus VSCode extension provides a way of converting a selection of HTML directly to RSX, so you can import templates from the web directly into your existing app.
It's also a bit easier on the eyes than HTML.
```rust
dioxus::ssr::render_lazy(rsx! {
div {
p {"Hello, {name}!"}
p {"Status: {pending}!"}
p {"Count {count}!"}
}
});
```
In the next section, we'll cover the `rsx!` macro in more depth.
@@ -0,0 +1,29 @@
## Testing
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
#[test]
fn component_runs() {
assert!(true)
}
```
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
#[dioxus::test]
fn runs_in_browser() {
// ...
}
```
Then, when you run
```console
dioxus test --chrome
```
Dioxus will build and test your code using the Chrome browser as a harness.
There's a lot more to testing if you dive in, so check out the [Testing]() guide for more information
@@ -0,0 +1,29 @@
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
rsx!(
Clickable {
"class": "blue-button",
"style": "background: red;"
}
)
```
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
#[derive(Props)]
struct ClickableProps<'a> {
attributes: Attributes<'a>
}
fn clickable(cx: Scope<ClickableProps<'a>>) -> Element {
cx.render(rsx!(
a {
..cx.props.attributes,
"Any link, anywhere"
}
))
}
+243
View File
@@ -0,0 +1,243 @@
# 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*.
Understanding the theory of reactive programming is essential to making sense of Dioxus and writing effective, performant UIs.
In this section, we'll talk about:
- One-way data flow
- Modifying data
- Forcing renders
- How renders propagate
This section is a bit long, but worth the read. We recommend coffee, tea, and/or snacks.
## 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.
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.
We consider the rendered GUI to be the final result of our Dioxus apps. The datasources for our apps include local and global state.
For example, the model presented in the figure below is comprised of two data sources: time and a constant. These values are passed through our computation graph to achieve a final result: `g`.
![Reactive Model](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e9/Reactive_programming_glitches.svg/440px-Reactive_programming_glitches.svg.png)
Whenever our `seconds` variable changes, we will then reevaluate the computation for `t`. Because `g` relies on `t`, we will also reevaluate its computation too. Notice that we would've reevaluated the computation for `g` even if `t` didn't change because `seconds` is used to calculate `g`.
However, if we somehow changed our constant from `1` to `2`, then we need to reevaluate `t`. If, for whatever reason, this change did not affect the result of `t`, then we wouldn't try to reevaluate `g`.
In Reactive Programming, we don't think about whether or not we should reevaluate `t` or `g`; instead, we simply provide functions of computation and let the framework figure out the rest for us.
In Rust, our reactive app would look something like:
```rust
fn compute_g(t: i32, seconds: i32) -> bool {
t > seconds
}
fn compute_t(constant: i32, seconds: i32) -> i32 {
constant + seconds
}
fn compute_graph(constant: i32, seconds: i32) -> bool {
let t = compute_t(constant, seconds);
let g = compute_g(t, seconds);
g
}
```
## How is Dioxus Reactive?
The Dioxus VirtualDom provides us a framework for reactive programming. When we build apps with dioxus, we need to provide our own datasources. This can be either initial props or some values fetched from the network. We then pass this data through our app into components through properties.
If we represented the reactive graph presented above in Dioxus, it would look very similar:
```rust
// Declare a component that holds our datasources and calculates `g`
fn RenderGraph(cx: Scope) -> Element {
let seconds = use_datasource(SECONDS);
let constant = use_state(&cx, || 1);
cx.render(rsx!(
RenderG { seconds: seconds }
RenderT { seconds: seconds, constant: constant }
))
}
// "calculate" g by rendering `t` and `seconds`
#[inline_props]
fn RenderG(cx: Scope, seconds: i32) -> Element {
cx.render(rsx!{ "There are {seconds} seconds remaining..." })
}
// calculate and render `t` in its own component
#[inline_props]
fn RenderT(cx: Scope, seconds: i32, constant: i32) -> Element {
let res = seconds + constant;
cx.render(rsx!{ "{res}" })
}
```
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.
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.
## How do we update values in our dataflow graph?
Dioxus will automatically figure out how to regenerate parts of our app when datasources change. But how exactly can we update our data sources?
In Dioxus there are two datasources:
1. Local state in `use_hook` and all other hooks
2. Global state through `provide_context`.
Technically, the root props of the VirtualDom are a third datasource, but since we cannot modify them, they are not worth talking about.
### Local State
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
fn app(cx: Scope) -> Element {
let mut count = cx.use_hook(|_| 0);
cx.render(rsx!{
button {
onclick: move |_| *count += 1,
"Count: {count}"
}
})
}
```
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
button {
onclick: move |_| {
*count += 1;
cx.needs_update();
},
"Count: {count}"
}
```
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.
### Understand this!
Your component functions will be called ("rendered" in our lingo) for as long as the component is present in the tree.
A single component will be called multiple times, modifying its own internal state or rendering new nodes with new values from its properties.
### App-Global State
With the `provide_context` and `consume_context` methods on `Scope`, we can share values to descendants without having to pass values through component props. This has the side-effect of making our datasources less obvious from a high-level perspective, but it makes our components more modular within the same codebase.
To make app-global state easier to reason about, Dioxus makes all values provided through `provide_context` immutable. This means any library built on top of `provide_context` needs to use interior mutability to modify shared global state.
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`:
```rust
let force_render = cx.schedule_update_any();
// force a render of the root component
force_render(ScopeId(0));
```
## What does it mean for a component to "re-render"?
In our guides, we frequently use the phrase "re-render" to describe updates to our app. You'll often hear this paired with "preventing unnecessary re-renders." But what exactly does this mean?
When we call `dioxus::desktop::launch`, Dioxus will create a new `Scope` object and call the component we gave it. Our `rsx!` calls will create new nodes which we return back to the VirtualDom. Dioxus will then look through these nodes for child components, call their functions, and so on until every component has been "rendered." We consider these nodes "rendered" because they were created because of our explicit actions.
The tree of UI that dioxus creates will roughly look like the tree of components presented earlier:
![Tree of UI](../images/component_tree.png)
But what happens when we call `needs_update` after modifying some important state? Well, if Dioxus called our component's function again, then we would produce new, different nodes. In fact, this is exactly what Dioxus does!
At this point, we have some old nodes and some new nodes. Again, we call this "rendering" because Dioxus had to create new nodes because of our explicit actions. Any time new nodes get created, our VirtualDom is being "rendered."
These nodes are stored in an extremely efficient memory allocator called a "bump arena." For example, a div with a handler and attribute would be stored in memory in two locations: the "old" tree and the "new" tree.
![Bump Arenas](../images/oldnew.png)
From here, Dioxus computes the difference between these trees and updates the Real DOM to make it look like the new version of what we've declared.
![Diffing](../images/diffing.png)
## 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?
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.
| props.val | re-render |
| --------- | --------- |
| 10 | true |
| 20 | true |
| 20 | false |
| 20 | false |
| 10 | true |
| 30 | false |
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
struct CustomProps {
val: i32,
}
impl PartialEq for CustomProps {
fn partial_eq(&self, other: &Self) -> bool {
// we don't render components that have a val less than 5
if other.val > 5 && self.val > 5{
self.val == other.val
}
}
}
```
However, for components that borrow data, it doesn't make sense to implement PartialEq since the actual references in memory might be different.
You can technically override this behavior by implementing the `Props` trait manually, though it's unsafe and easy to mess up:
```rust
unsafe impl Properties for CustomProps {
fn memoize(&self, other &Self) -> bool {
self != other
}
}
```
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
## Wrapping Up
Wow, that was a lot of material!
Let's see if we can recap what was presented:
- Reactive programming calculates a final value from datasources and computation
- Dioxus is "reactive" since it figures out which computations to check
- `schedule_update` must be called to mark a component as dirty
- dirty components will be re-rendered (called multiple times) to produce a new UI
- Renders can be suppressed with memoization
This theory is crucial to understand how to compose components and how to control renders in your app.
@@ -0,0 +1,26 @@
## JavaScript Handlers
Instead of passing a closure, you can also pass a string to event handlers – this lets you use JavaScript (if your renderer can execute JavaScript):
```rust
{{#include ../../examples/event_javascript.rs:rsx}}
```
#![allow(non_snake_case)]
use dioxus::prelude::*;
fn main() {
dioxus::desktop::launch(App);
}
fn App(cx: Scope) -> Element {
cx.render(rsx! {
// ANCHOR: rsx
div {
onclick: "alert('hello world')",
}
// ANCHOR_END: rsx
})
}
+61
View File
@@ -0,0 +1,61 @@
# Fanning Out
One of the most reliable state management patterns in large Dioxus apps is `fan-out`. The fan-out pattern is the ideal way to structure your app to maximize code reuse, testability, and deterministic rendering.
## The structure
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
#[derive(Props, PartialEq)]
struct TitlebarProps {
title: String,
subtitle: String,
}
fn Titlebar(cx: Scope<TitlebarProps>) -> Element {
cx.render(rsx!{
div {
class: "titlebar"
h1 { "{cx.props.title}" }
h1 { "{cx.props.subtitle}" }
}
})
}
```
If we used global state like use_context or fermi, we might be tempted to inject our `use_read` directly into the component.
```rust
fn Titlebar(cx: Scope<TitlebarProps>) -> Element {
let title = use_read(&cx, TITLE);
let subtitle = use_read(&cx, SUBTITLE);
cx.render(rsx!{/* ui */})
}
```
For many apps – this is a fine pattern, especially if the component is a one-off. However, if we want to reuse the component outside of this app, then we'll start to run into issues where our contexts are unavailable.
## Fanning Out
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
fn DocsiteTitlesection(cx: Scope) {
let title = use_read(&cx, TITLE);
let subtitle = use_read(&cx, SUBTITLE);
let username = use_read(&cx, USERNAME);
let points = use_read(&cx, POINTS);
cx.render(rsx!{
TitleBar { title: title, subtitle: subtitle }
UserBar { username: username, points: points }
})
}
```
This particular wrapper component unfortunately cannot be reused across apps. However, because it simply wraps other real elements, it doesn't have to. We are free to reuse our TitleBar and UserBar components across apps with ease. We also know that this particular component is plenty performant because the wrapper doesn't have any props and is always memoized. The only times this component re-renders is when any of the atoms change.
This is the beauty of Dioxus – we always know where our components are likely to be re-rendered. Our wrapper components can easily prevent any large re-renders by simply memoizing their components. This system might not be as elegant or precise as signal systems found in libraries like Sycamore or SolidJS, but it is quite ergonomic.
+14
View File
@@ -0,0 +1,14 @@
# "Hello, World" desktop app
If you plan to develop extensions for the `Dioxus` ecosystem, please use the `dioxus` crate with the `core` feature to limit the amount of dependencies your project brings in.
### What is this `Scope` object?
Coming from React, the `Scope` object might be confusing. In React, you'll want to store data between renders with hooks. However, hooks rely on global variables which make them difficult to integrate in multi-tenant systems like server-rendering.
In Dioxus, you are given an explicit `Scope` object to control how the component renders and stores data. The `Scope` object provides a handful of useful APIs for features like suspense, rendering, and more.
For now, just know that `Scope` lets you store state with hooks and render elements with `cx.render`.
+47
View File
@@ -0,0 +1,47 @@
# Helper Crates
Because the Dioxus ecosystem is fairly young, there aren't a ton of third-party libraries designed to "get things done." That's where the Dioxus helper crates come in. These are officially supported crates built on top of existing libraries to solve some of the common barriers to building apps.
## Router
Quickly add a cross-platform router to structure your app.
[Link](https://github.com/DioxusLabs/dioxus/tree/master/packages/router)
## Fermi
Global state as easy as `use_state`.
[Link](https://github.com/DioxusLabs/dioxus/tree/master/packages/fermi)
## Query
This crate has yet to be developed! However, we do plan on providing a crate for good fetching and query support.
## 3rd-party – Toast
Toast notifications, curtesy of [@mrxiaozhuox](https://github.com/mrxiaozhuox).
[Link](https://github.com/mrxiaozhuox/dioxus-toast)
## 3rd-party – HeroIcon
Collection of helpful hero icons, curtesy of [@autarch](https://github.com/autarch).
[Link](https://github.com/houseabsolute/dioxus-heroicons)
## 3rd-party – Katex
Draw beautiful equations, curtesy of [@oovm](https://github.com/oovm)
[Link](https://github.com/oovm/katex-wasm/tree/dev/projects/dioxus-katex)
## 3rd-party – PrimsJS
Highlight your code blocks with ease, curtesy of [@oovm](https://github.com/oovm)
[Link](https://github.com/oovm/katex-wasm/tree/dev/projects/dioxus-katex)
+38
View File
@@ -0,0 +1,38 @@
# Managing State
Every app you'll build with Dioxus will have some sort of state that needs to be maintained and updated as your users interact with it. However, managing state can be particularly challenging at times, and is frequently the source of bugs in many GUI frameworks.
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.
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
let all_content = get_all_content().await;
let output = dioxus::ssr::render_lazy(rsx!{
div {
RenderContent { content: all_content }
}
});
```
With this incredibly simple setup, it is highly unlikely that you'll have rendering bugs. There simply is barely any state to manage.
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:
- Refactor state out of shared state and into reusable components and hooks.
- Lift state upwards to be spread across multiple components (fan out).
- Use the Context API to share state globally.
- Use a dedicated state management solution like Fermi.
+110
View File
@@ -0,0 +1,110 @@
# Local State
The first step to dealing with complexity in your app is to refactor your state to be purely local. This encourages good code reuse and prevents leakage of abstractions across component boundaries.
## What it looks like
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
struct Todo {
contents: String,
is_hovered: bool,
is_editing: bool,
}
let todos = use_ref(&cx, || vec![Todo::new()]);
cx.render(rsx!{
ul {
todos.read().iter().enumerate().map(|(id, todo)| rsx!{
li {
onhover: move |_| *todos.write()[id].is_hovered = true,
h1 { "{todo.contents}" }
}
})
}
})
```
As shown above, whenever the todo is hovered, we want to set its state:
```rust
todos.write()[0].is_hovered = true;
```
As the amount of interactions goes up, so does the complexity of our state. Should the "hover" state really be baked into our data model?
Instead, let's refactor our Todo component to handle its own state:
```rust
#[inline_props]
fn Todo<'a>(cx: Scope, todo: &'a Todo) -> Element {
let is_hovered = use_state(&cx, || false);
cx.render(rsx!{
li {
h1 { "{todo.contents}" }
onhover: move |_| is_hovered.set(true),
}
})
}
```
Now, we can simplify our Todo data model to get rid of local UI state:
```rust
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.
Wherever possible, you should try to refactor the "view" layer *out* of your data model.
## Immutability
Storing all of your state inside a `use_ref` might be tempting. However, you'll quickly run into an issue where the `Ref` provided by `read()` "does not live long enough." An indeed – you can't return locally-borrowed value into the Dioxus tree.
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
struct State {
count: i32,
color: &'static str,
names: HashMap<String, String>
}
// in the component
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
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.
When combined with the `make_mut` method on `use_state`, you can get really succinct updates to collections:
```rust
let todos = use_state(&cx, im_rc::HashMap::default);
todos.make_mut().insert("new todo", Todo {
contents: "go get groceries",
});
```
## 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.
+28
View File
@@ -0,0 +1,28 @@
## 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
fn Demo(cx: Scope) -> Element {
// don't worry about these 2, we'll cover them later
let name = use_state(&cx, || String::from("bob"));
let age = use_state(&cx, || 21);
cx.render(rsx!{
Name { name: name }
Age { age: age }
})
}
```
If `name` changes but `age` does not, then there is no reason to re-render our `Age` component since the contents of its props did not meaningfully change.
Dioxus memoizes owned components. It uses `PartialEq` to determine if a component needs rerendering, or if it has stayed the same. This is why you must derive PartialEq!
> 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.
@@ -0,0 +1,67 @@
## 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
struct Calculator {
display_value: String,
operator: Option<Operator>,
waiting_for_operand: bool,
cur_val: f64,
}
```
Our component is really simple – we just call `use_ref` to get an initial calculator state.
```rust
fn app(cx: Scope) -> Element {
let state = use_ref(&cx, Calculator::new);
cx.render(rsx!{
// the rendering code
})
}
```
In our UI, we can then use `read` and a helper method to get data out of the model.
```rust
// Our accessor method
impl Calculator {
fn formatted_display(&self) -> String {
self.display_value
.parse::<f64>()
.unwrap()
.separated_string()
}
}
// And then in the UI
cx.render(rsx!{
div { [state.read().formatted_display()] }
})
```
To modify the state, we can setup a helper method and then attach it to a callback.
```rust
// our helper
impl Calculator {
fn clear_display(&mut self) {
self.display_value = "0".to_string()
}
}
// our callback
cx.render(rsx!{
button {
onclick: move |_| state.write().clear_display(),
}
})
```