Function Signature
Parameters
A closure that returns the initial value for the state. This closure is only called once during component initialization.
Return Type
Returns aState<T> that implements Copy, making it cheap to pass around. Components automatically re-render when the state value changes.
Key Features
- Reactive: Components automatically re-render when the state value changes
- Copy:
State<T>implementsCopy, no need to clone - Shared: Multiple components can read from and write to the same state
- Scoped: State is automatically cleaned up when its owning component unmounts
Basic Usage
Reading State
read() - Subscribe to changes
Reads the current value and subscribes the component to changes:
peek() - Read without subscribing
Reads the value without subscribing (component won’t re-render):
Writing State
write() - Get mutable reference
Get a mutable reference to modify the value:
set() - Replace the value
Replace the entire value:
with_mut() - Modify using a closure
Modify the value using a closure:
Conditional Updates
set_if_modified() - Update only if different
Only updates if the new value differs from the current value:
set_if_modified_and_then() - Update and run callback
Updates if different and executes a callback:
Working with Options
ForState<Option<T>>, you can use take() to move the value out:
Boolean Toggle
For types that implementNot (like bool):
Copy Types Shorthand
ForCopy types, you can call the state as a function:
When to Use
Useuse_state when you need:
- Mutable state within a component
- Reactive updates that trigger re-renders
- Simple local state management
- Global state: Use
State::create_global()or thefreya-radiocrate - Derived values: Use
use_memofor expensive computations - Side effects: Use
use_side_effectto react to state changes
Performance Notes
- Reading state with
read()subscribes the component, causing re-renders when it changes - Use
peek()only when you specifically don’t want reactivity - Prefer
set_if_modified()overset()when the value might not have changed State<T>isCopy, so no need to clone it when passing to closures
Thread Safety
State<T> is not thread-safe and should only be used within the main UI thread. For cross-thread communication, use channels or other synchronization primitives.