Skip to main content
Version: Next

State

General view of how to store state

This table can be used as a guide when deciding what state-storing type fits best for your use case:

HookTypeRerender when?Scope
use_stateTgot setcomponent instance
use_state_eqT: PartialEqgot set with diff. valuecomponent instance
use_reducerT: Reduciblegot reducedcomponent instance
use_reducer_eqT: Reducible + PartialEqgot reduced with diff. valuecomponent instance
use_memoDeps -> Tdependencies changedcomponent instance
use_callbackDeps -> Callback<E>dependencies changedcomponent instance
use_mut_refT-component instance
a static global variableT-global, used by all

Accessing handle internals

Both UseStateHandle and UseReducerHandle provide methods to access their internal parts directly.

value_rc()

Returns the current value wrapped in an Rc<T>. Unlike dereferencing the handle (which gives a &T tied to the handle's lifetime), value_rc() gives you an owned Rc<T> that can be moved into closures or stored independently.

# use std::rc::Rc;
# use yew::prelude::*;
# #[component]
# fn Comp() -> Html {
let counter = use_state(|| 0);
let rc_value: Rc<i32> = counter.value_rc();
# html! {}
# }

into_inner()

Consumes the handle and returns its two parts: the current value as Rc<T> and the setter/dispatcher. This is useful when you want to separate reading from writing without cloning the full handle.

For UseReducerHandle, the return type is (Rc<T>, UseReducerDispatcher<T>):

# use std::rc::Rc;
# use yew::prelude::*;
# #[derive(Default, PartialEq)]
# struct CounterState { counter: i32 }
# impl Reducible for CounterState {
# type Action = ();
# fn reduce(self: Rc<Self>, _: ()) -> Rc<Self> { self }
# }
# #[component]
# fn Comp() -> Html {
let state = use_reducer(CounterState::default);
let (value, dispatcher) = state.into_inner();
# html! {}
# }

For UseStateHandle, the return type is (Rc<T>, UseStateSetter<T>):

# use std::rc::Rc;
# use yew::prelude::*;
# #[component]
# fn Comp() -> Html {
let state = use_state(|| 0);
let (value, setter) = state.into_inner();
# html! {}
# }