-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
use_callback.rs
89 lines (86 loc) · 2.39 KB
/
use_callback.rs
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
88
89
use std::rc::Rc;
use crate::callback::Callback;
use crate::functional::{hook, use_memo};
/// Get a immutable reference to a memoized `Callback`.
///
/// Memoization means it will only get recreated when provided dependencies update/change.
/// This is useful when passing callbacks to optimized child components that rely on
/// PartialEq to prevent unnecessary renders.
///
/// # Example
///
/// ```rust
/// # use yew::prelude::*;
/// #
/// #[derive(Properties, PartialEq)]
/// pub struct Props {
/// pub callback: Callback<String, String>,
/// }
///
/// #[function_component(MyComponent)]
/// fn my_component(props: &Props) -> Html {
/// let greeting = props.callback.emit("Yew".to_string());
///
/// html! {
/// <>{ &greeting }</>
/// }
/// }
///
/// #[function_component(UseCallback)]
/// fn callback() -> Html {
/// let counter = use_state(|| 0);
/// let onclick = {
/// let counter = counter.clone();
/// Callback::from(move |_| counter.set(*counter + 1))
/// };
///
/// // This callback depends on (), so it's created only once, then MyComponent
/// // will be rendered only once even when you click the button mutiple times.
/// let callback = use_callback(
/// move |name, _| format!("Hello, {}!", name),
/// ()
/// );
///
/// // It can also be used for events, this callback depends on `counter`.
/// let oncallback = {
/// let counter = counter.clone();
/// use_callback(
/// move |_e, counter| {
/// let _ = **counter;
/// },
/// counter
/// )
/// };
///
/// html! {
/// <div>
/// <button {onclick}>{ "Increment value" }</button>
/// <button onclick={oncallback}>{ "Callback" }</button>
/// <p>
/// <b>{ "Current value: " }</b>
/// { *counter }
/// </p>
/// <MyComponent {callback} />
/// </div>
/// }
/// }
/// ```
#[hook]
pub fn use_callback<IN, OUT, F, D>(f: F, deps: D) -> Callback<IN, OUT>
where
IN: 'static,
OUT: 'static,
F: Fn(IN, &D) -> OUT + 'static,
D: PartialEq + 'static,
{
let deps = Rc::new(deps);
(*use_memo(
move |deps| {
let deps = deps.clone();
let f = move |value: IN| f(value, deps.as_ref());
Callback::from(f)
},
deps,
))
.clone()
}