yew_hooks/hooks/
use_effect_update.rs

1use yew::prelude::*;
2
3use super::use_is_first_mount;
4
5/// This hook ignores the first invocation (e.g. on mount).
6/// The signature is exactly the same as the [`use_effect`] hook.
7///
8/// # Example
9///
10/// ```rust
11/// # use yew::prelude::*;
12/// # use log::debug;
13/// #
14/// use yew_hooks::prelude::*;
15///
16/// #[function_component(UseEffectUpdate)]
17/// fn effect_update() -> Html {
18///     use_effect_update(|| {
19///         debug!("Running effect only on updates");
20///
21///         || ()
22///     });
23///     
24///     html! {
25///         <>
26///         </>
27///     }
28/// }
29/// ```
30#[hook]
31pub fn use_effect_update<Callback, Destructor>(callback: Callback)
32where
33    Callback: FnOnce() -> Destructor + 'static,
34    Destructor: FnOnce() + 'static,
35{
36    let first = use_is_first_mount();
37
38    use_effect(move || {
39        if first {
40            Box::new(|| ()) as Box<dyn FnOnce()>
41        } else {
42            Box::new(callback())
43        }
44    });
45}
46
47/// This hook is similar to [`use_effect_update`] but it accepts dependencies.
48/// The signature is exactly the same as the [`use_effect_with`] hook.
49#[hook]
50pub fn use_effect_update_with_deps<Callback, Destructor, Dependents>(
51    callback: Callback,
52    deps: Dependents,
53) where
54    Callback: FnOnce(&Dependents) -> Destructor + 'static,
55    Destructor: FnOnce() + 'static,
56    Dependents: PartialEq + 'static,
57{
58    let first = use_is_first_mount();
59
60    use_effect_with(deps, move |deps| {
61        if first {
62            Box::new(|| ()) as Box<dyn FnOnce()>
63        } else {
64            Box::new(callback(deps))
65        }
66    });
67}