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