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

Function use_effect

Source
pub fn use_effect<'hook, F, D>(f: F) -> impl 'hook + Hook<Output = ()>
where F: FnOnce() -> D + 'static + 'hook, D: TearDown + 'hook,
Expand description

use_effect is used for hooking into the component’s lifecycle and creating side effects.

The callback is called every time after the component’s render has finished.

§Example

use yew::prelude::*;

#[function_component(UseEffect)]
fn effect() -> Html {
    let counter = use_state(|| 0);

    let counter_one = counter.clone();
    use_effect(move || {
        // Make a call to DOM API after component is rendered
        gloo::utils::document().set_title(&format!("You clicked {} times", *counter_one));

        // Perform the cleanup
        || gloo::utils::document().set_title(&format!("You clicked 0 times"))
    });

    let onclick = {
        let counter = counter.clone();
        Callback::from(move |_| counter.set(*counter + 1))
    };

    html! {
        <button {onclick}>{ format!("Increment to {}", *counter) }</button>
    }
}

§Destructor

Any type implementing TearDown can be used as destructor, which is called when the component is re-rendered

§Tip

The callback can return [()] if there is no destructor to run.

§Note

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

pub fn use_effect<F, D>(f: F)
where
    F: FnOnce() -> D + 'static,
    D: TearDown,
{
    /* implementation omitted */
}