pub fn use_state<'hook, T, F>(
init_fn: F,
) -> impl 'hook + Hook<Output = UseStateHandle<T>>where
T: 'static + 'hook,
F: FnOnce() -> T + 'hook,
Expand description
This hook is used to manage state in a function component.
This hook will always trigger a re-render upon receiving a new state. See use_state_eq
if you want the component to only re-render when the new state compares unequal
to the existing one.
§Example
use yew::prelude::*;
#[function_component(UseState)]
fn state() -> Html {
let counter = use_state(|| 0);
let onclick = {
let counter = counter.clone();
Callback::from(move |_| counter.set(*counter + 1))
};
html! {
<div>
<button {onclick}>{ "Increment value" }</button>
<p>
<b>{ "Current value: " }</b>
{ *counter }
</p>
</div>
}
}
§Caution
The value held in the handle will reflect the value of at the time the
handle is returned by the use_state()
call. It is possible that the handle does
not dereference to an up to date value, for example if you are moving it into a
use_effect_with
hook. You can register the
state to the dependents so the hook can be updated when the value changes.
§Tip
The setter function is guaranteed to be the same across the entire
component lifecycle. You can safely omit the UseStateHandle
from the
dependents of use_effect_with
if you only intend to set
values from within the hook.
§Note
When used in function components and hooks, this hook is equivalent to:
pub fn use_state<T, F>(init_fn: F) -> UseStateHandle<T>
where
T: 'static,
F: FnOnce() -> T,
{
/* implementation omitted */
}