pub fn use_effect_with<T, F, D>(deps: T, f: F) -> impl Hook<Output = ()>
Expand description
This hook is similar to use_effect
but it accepts dependencies.
Whenever the dependencies are changed, the effect callback is called again.
To detect changes, dependencies must implement PartialEq
.
§Note
The destructor also runs when dependencies change.
§Example
use yew::{function_component, html, use_effect_with, Html, Properties};
#[derive(Properties, PartialEq)]
pub struct Props {
pub is_loading: bool,
}
#[function_component]
fn HelloWorld(props: &Props) -> Html {
let is_loading = props.is_loading.clone();
use_effect_with(is_loading, move |_| {
log!(" Is loading prop changed!");
});
html! {
<>{"Am I loading? - "}{is_loading}</>
}
}
§Tips
§Only on first render
Provide a empty tuple ()
as dependencies when you need to do something only on the first
render of a component.
use yew::{function_component, html, use_effect_with, Html};
#[function_component]
fn HelloWorld() -> Html {
use_effect_with((), move |_| {
log!("I got rendered, yay!");
});
html! { "Hello" }
}
§On destructing or last render
Use Only on first render but put the code in the cleanup function. It will only get called when the component is removed from view / gets destroyed.
use yew::{function_component, html, use_effect_with, Html};
#[function_component]
fn HelloWorld() -> Html {
use_effect_with((), move |_| {
|| {
log!("Noo dont kill me, ahhh!");
}
});
html! { "Hello" }
}
Any type implementing TearDown
can be used as destructor
§Tip
The callback can return [()
] if there is no destructor to run.