This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.

Function yew::functional::use_memo

source ·
pub fn use_memo<'hook, T, F, D>(
    deps: D,
    f: F
) -> impl 'hook + Hook<Output = Rc<T>>
where T: 'static + 'hook, F: FnOnce(&D) -> T + 'hook, D: 'static + PartialEq + 'hook,
Expand description

Get a immutable reference to a memoized value.

Memoization means it will only get recalculated when provided dependencies update/change.

It can be useful for keeping things in scope for the lifetime of the component, so long as you don’t store a clone of the resulting Rc anywhere that outlives the component.

§Example

use yew::prelude::*;

#[derive(PartialEq, Properties)]
pub struct Props {
    pub step: usize,
}

#[function_component(UseMemo)]
fn memo(props: &Props) -> Html {
    // Will only get recalculated if `props.step` value changes
    let message = use_memo(props.step, |step| {
        format!("{}. Do Some Expensive Calculation", step)
    });

    html! {
        <div>
            <span>{ (*message).clone() }</span>
        </div>
    }
}

§Note

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

pub fn use_memo<T, F, D>(deps: D, f: F) -> Rc<T>
where
    T: 'static,
    F: FnOnce(&D) -> T,
    D: 'static + PartialEq,
{
    /* implementation omitted */
}