yew_hooks/hooks/use_unmount.rs
1use yew::prelude::*;
2
3use super::{use_effect_once, use_mut_latest};
4
5/// A lifecycle hook that calls a function when the component will unmount.
6///
7/// # Example
8///
9/// ```rust
10/// # use yew::prelude::*;
11/// # use log::debug;
12/// #
13/// use yew_hooks::prelude::*;
14///
15/// #[function_component(Unmount)]
16/// fn unmount() -> Html {
17/// use_unmount(|| {
18/// debug!("Running clean-up of effect on unmount");
19/// });
20///
21/// html! {
22/// <>
23/// </>
24/// }
25/// }
26/// ```
27#[hook]
28pub fn use_unmount<Callback>(callback: Callback)
29where
30 Callback: FnOnce() + 'static,
31{
32 let callback_ref = use_mut_latest(Some(callback));
33
34 use_effect_once(move || {
35 move || {
36 let callback_ref = callback_ref.current();
37 let callback = (*callback_ref.borrow_mut()).take();
38 if let Some(callback) = callback {
39 callback();
40 }
41 }
42 });
43}