yew/functional/hooks/use_state.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
use std::fmt;
use std::ops::Deref;
use std::rc::Rc;
use super::{use_reducer, use_reducer_eq, Reducible, UseReducerDispatcher, UseReducerHandle};
use crate::functional::hook;
use crate::html::IntoPropValue;
use crate::Callback;
struct UseStateReducer<T> {
value: T,
}
impl<T> Reducible for UseStateReducer<T> {
type Action = T;
fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
Rc::new(Self { value: action })
}
}
impl<T> PartialEq for UseStateReducer<T>
where
T: PartialEq,
{
fn eq(&self, rhs: &Self) -> bool {
self.value == rhs.value
}
}
/// 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
///
/// ```rust
/// use yew::prelude::*;
/// # use std::rc::Rc;
///
/// #[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.
#[hook]
pub fn use_state<T, F>(init_fn: F) -> UseStateHandle<T>
where
T: 'static,
F: FnOnce() -> T,
{
let handle = use_reducer(move || UseStateReducer { value: init_fn() });
UseStateHandle { inner: handle }
}
/// [`use_state`] but only re-renders when `prev_state != next_state`.
///
/// This hook requires the state to implement [`PartialEq`].
#[hook]
pub fn use_state_eq<T, F>(init_fn: F) -> UseStateHandle<T>
where
T: PartialEq + 'static,
F: FnOnce() -> T,
{
let handle = use_reducer_eq(move || UseStateReducer { value: init_fn() });
UseStateHandle { inner: handle }
}
/// State handle for the [`use_state`] hook.
pub struct UseStateHandle<T> {
inner: UseReducerHandle<UseStateReducer<T>>,
}
impl<T: fmt::Debug> fmt::Debug for UseStateHandle<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UseStateHandle")
.field("value", &format!("{:?}", self.inner.value))
.finish()
}
}
impl<T> UseStateHandle<T> {
/// Replaces the value
pub fn set(&self, value: T) {
self.inner.dispatch(value)
}
/// Returns the setter of current state.
pub fn setter(&self) -> UseStateSetter<T> {
UseStateSetter {
inner: self.inner.dispatcher(),
}
}
}
impl<T> Deref for UseStateHandle<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&(*self.inner).value
}
}
impl<T> Clone for UseStateHandle<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> PartialEq for UseStateHandle<T>
where
T: PartialEq,
{
fn eq(&self, rhs: &Self) -> bool {
*self.inner == *rhs.inner
}
}
/// Setter handle for [`use_state`] and [`use_state_eq`] hook
pub struct UseStateSetter<T> {
inner: UseReducerDispatcher<UseStateReducer<T>>,
}
impl<T> Clone for UseStateSetter<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> fmt::Debug for UseStateSetter<T>
where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("UseStateSetter").finish()
}
}
impl<T> From<UseStateSetter<T>> for Callback<T> {
fn from(value: UseStateSetter<T>) -> Self {
Self::from(value.inner)
}
}
impl<T> IntoPropValue<Callback<T>> for UseStateSetter<T> {
fn into_prop_value(self) -> Callback<T> {
self.inner.into_prop_value()
}
}
impl<T> PartialEq for UseStateSetter<T> {
fn eq(&self, rhs: &Self) -> bool {
self.inner == rhs.inner
}
}
impl<T> UseStateSetter<T> {
/// Replaces the value
pub fn set(&self, value: T) {
self.inner.dispatch(value)
}
/// Get a callback, invoking which is equivalent to calling `set()`
/// on this same setter.
pub fn to_callback(&self) -> Callback<T> {
self.inner.to_callback()
}
}