Function yew::functional::use_effect_with_deps
source · pub fn use_effect_with_deps<'hook, T, F, D>(
f: F,
deps: T
) -> impl 'hook + Hook<Output = ()>where
T: PartialEq + 'static,
F: FnOnce(&T) -> D + 'static,
D: TearDown,
T: 'hook,
F: 'hook,
D: 'hook,
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_deps, 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_deps(
move |_| {
log!(" Is loading prop changed!");
},
is_loading,
);
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_deps, Html};
#[function_component]
fn HelloWorld() -> Html {
use_effect_with_deps(
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_deps, Html};
#[function_component]
fn HelloWorld() -> Html {
use_effect_with_deps(
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.
Note
When used in function components and hooks, this hook is equivalent to:
pub fn use_effect_with_deps<T, F, D>(f: F, deps: T)
where
T: PartialEq + 'static,
F: FnOnce(&T) -> D + 'static,
D: TearDown,
{
/* implementation omitted */
}