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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
use yew::prelude::*;
use super::{use_throttle, use_unmount};
/// A hook that throttles calling effect callback, it is only called once every `millis`.
///
/// # Example
///
/// ```rust
/// # use yew::prelude::*;
/// #
/// use yew_hooks::prelude::*;
///
/// #[function_component(ThrottleEffect)]
/// fn throttle_effect() -> Html {
/// let state = use_state(|| 0);
/// let update = use_update();
///
/// {
/// let state = state.clone();
/// use_throttle_effect(
/// move || {
/// state.set(*state + 1);
/// },
/// 2000,
/// )
/// };
///
/// let onclick = { Callback::from(move |_| update()) };
///
/// html! {
/// <>
/// <button {onclick}>{ "Click fast!" }</button>
/// <b>{ "State: " }</b> {*state}
/// </>
/// }
/// }
/// ```
#[hook]
pub fn use_throttle_effect<Callback>(callback: Callback, millis: u32)
where
Callback: FnMut() + 'static,
{
let throttle = use_throttle(callback, millis);
{
let throttle = throttle.clone();
use_effect(move || {
throttle.run();
|| ()
});
}
use_unmount(move || {
throttle.cancel();
});
}
/// This hook is similar to [`use_throttle_effect`] but it accepts dependencies.
///
/// Whenever the dependencies are changed, the throttle effect is run again.
/// To detect changes, dependencies must implement `PartialEq`.
#[hook]
pub fn use_throttle_effect_with_deps<Callback, Dependents>(
callback: Callback,
millis: u32,
deps: Dependents,
) where
Callback: FnMut() + 'static,
Dependents: PartialEq + 'static,
{
let throttle = use_throttle(callback, millis);
{
let throttle = throttle.clone();
use_effect_with(deps, move |_| {
throttle.run();
|| ()
});
}
use_unmount(move || {
throttle.cancel();
});
}