wasm_react/hooks/deps.rs
1use std::fmt::Debug;
2
3/// This struct specifies dependencies for certain hooks.
4///
5/// # Example
6///
7/// ```
8/// # use wasm_react::{*, hooks::*};
9/// # fn log(s: &str) {}
10/// # struct State { counter: () }
11/// # struct F { id: () };
12/// # impl F {
13/// # fn f(&self, state: State) {
14/// #
15/// use_effect(|| {
16/// log("This effect will be called every time `self.id` or `state.counter` changes.");
17/// }, Deps::some((self.id, state.counter)));
18/// #
19/// # }
20/// # }
21/// ```
22#[derive(PartialEq, Clone, Copy)]
23pub struct Deps<T>(Option<T>);
24
25impl<T: Debug> Debug for Deps<T> {
26 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 let mut result = f.debug_tuple("Deps");
28
29 match self.0.as_ref() {
30 Some(deps) => result.field(&deps),
31 None => result.field(&"All"),
32 }
33 .finish()
34 }
35}
36
37impl Deps<()> {
38 /// The hook will be activated whenever the component renders.
39 pub fn all() -> Self {
40 Self(None)
41 }
42
43 /// The hook will be activated only on the first render.
44 pub fn none() -> Self {
45 Self(Some(()))
46 }
47}
48
49impl<T> Deps<T> {
50 /// The hook will be activated every time when the component renders if the
51 /// inner value `T` has changed from last render.
52 pub fn some(deps: T) -> Self {
53 Self(Some(deps))
54 }
55
56 pub(crate) fn is_all(&self) -> bool {
57 self.0.is_none()
58 }
59}