yew_hooks/hooks/use_throttle_effect.rs
1use yew::prelude::*;
2
3use super::{use_throttle, use_unmount};
4
5/// A hook that throttles calling effect callback, it is only called once every `millis`.
6///
7/// # Example
8///
9/// ```rust
10/// # use yew::prelude::*;
11/// #
12/// use yew_hooks::prelude::*;
13///
14/// #[function_component(ThrottleEffect)]
15/// fn throttle_effect() -> Html {
16/// let state = use_state(|| 0);
17/// let update = use_update();
18///
19/// {
20/// let state = state.clone();
21/// use_throttle_effect(
22/// move || {
23/// state.set(*state + 1);
24/// },
25/// 2000,
26/// )
27/// };
28///
29/// let onclick = { Callback::from(move |_| update()) };
30///
31/// html! {
32/// <>
33/// <button {onclick}>{ "Click fast!" }</button>
34/// <b>{ "State: " }</b> {*state}
35/// </>
36/// }
37/// }
38/// ```
39#[hook]
40pub fn use_throttle_effect<Callback>(callback: Callback, millis: u32)
41where
42 Callback: FnMut() + 'static,
43{
44 let throttle = use_throttle(callback, millis);
45
46 {
47 let throttle = throttle.clone();
48 use_effect(move || {
49 throttle.run();
50
51 || ()
52 });
53 }
54
55 use_unmount(move || {
56 throttle.cancel();
57 });
58}
59
60/// This hook is similar to [`use_throttle_effect`] but it accepts dependencies.
61///
62/// Whenever the dependencies are changed, the throttle effect is run again.
63/// To detect changes, dependencies must implement `PartialEq`.
64#[hook]
65pub fn use_throttle_effect_with_deps<Callback, Dependents>(
66 callback: Callback,
67 millis: u32,
68 deps: Dependents,
69) where
70 Callback: FnMut() + 'static,
71 Dependents: PartialEq + 'static,
72{
73 let throttle = use_throttle(callback, millis);
74
75 {
76 let throttle = throttle.clone();
77 use_effect_with(deps, move |_| {
78 throttle.run();
79
80 || ()
81 });
82 }
83
84 use_unmount(move || {
85 throttle.cancel();
86 });
87}