Function use_latest

Source
pub fn use_latest<'hook, T>(
    value: T,
) -> impl 'hook + Hook<Output = UseLatestHandle<T>>
where T: 'static + 'hook,
Expand description

This hook returns the latest immutable ref to state or props.

§Example

use yew_hooks::prelude::*;

#[function_component(UseLatest)]
fn latest() -> Html {
    let state = use_state(|| 0);
    let interval = use_mut_ref(|| None);

    let latest_state = use_latest(state.clone());

    {
        let state = state.clone();
        use_effect_with((), move |_| {
            *interval.borrow_mut() = Some(Interval::new(1000, move || {
                // This will get the latest state and increase it by 1 each time.
                state.set(**latest_state.current() + 1);
            }));
            move || *interval.borrow_mut() = None
        });
    }
    
    html! {
        <div>
            <p>
                <b>{ "Latest value: " }</b>
                { *state }
            </p>
        </div>
    }
}

§Note

When used in function components and hooks, this hook is equivalent to:

pub fn use_latest<T>(value: T) -> UseLatestHandle<T>
where
    T: 'static,
{
    /* implementation omitted */
}