yew_hooks/hooks/
use_state_ptr_eq.rs

1use std::ops::Deref;
2use std::rc::Rc;
3
4use yew::prelude::*;
5
6struct UseStatePtrEqReducer<T> {
7    value: Rc<T>,
8}
9
10impl<T> Reducible for UseStatePtrEqReducer<T> {
11    type Action = T;
12    fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
13        Rc::new(Self {
14            value: action.into(),
15        })
16    }
17}
18
19impl<T> PartialEq for UseStatePtrEqReducer<T> {
20    fn eq(&self, rhs: &Self) -> bool {
21        // Check if the two `Rc`s point to the same allocation, instead of PartialEq of the values.
22        Rc::ptr_eq(&self.value, &rhs.value)
23    }
24}
25
26/// State handle for the [`use_state_ptr_eq`] hook.
27pub struct UseStatePtrEqHandle<T> {
28    inner: UseReducerHandle<UseStatePtrEqReducer<T>>,
29}
30
31impl<T> UseStatePtrEqHandle<T> {
32    /// Replaces the value
33    pub fn set(&self, value: T) {
34        self.inner.dispatch(value);
35    }
36}
37
38impl<T> Deref for UseStatePtrEqHandle<T> {
39    type Target = T;
40
41    fn deref(&self) -> &Self::Target {
42        &(*self.inner).value
43    }
44}
45
46impl<T> Clone for UseStatePtrEqHandle<T> {
47    fn clone(&self) -> Self {
48        Self {
49            inner: self.inner.clone(),
50        }
51    }
52}
53
54impl<T> PartialEq for UseStatePtrEqHandle<T>
55where
56    T: PartialEq,
57{
58    fn eq(&self, rhs: &Self) -> bool {
59        *self.inner == *rhs.inner
60    }
61}
62
63/// Similar to `use_state_eq`, but check if the two `Rc`s of values point to the same allocation,
64/// instead of PartialEq of the values.
65///
66/// # Example
67///
68/// ```rust
69/// # use yew::prelude::*;
70/// #
71/// use yew_hooks::prelude::*;
72///
73/// #[function_component(UseStatePtrEq)]
74/// fn state_ptr_eq() -> Html {
75///     let state = use_state_ptr_eq(|| "".to_string());
76///
77///     let onclick = {
78///         let state = state.clone();
79///         Callback::from(move |_| {
80///             state.set("Hello, world!".to_string());
81///         })
82///     };
83///     
84///     html! {
85///         <>
86///             <button {onclick}>{ "Hello, world!" }</button>
87///             <p>
88///                 <b>{ "Current value: " }</b>
89///                 { &*state }
90///             </p>
91///         </>
92///     }
93/// }
94/// ```
95#[hook]
96pub fn use_state_ptr_eq<T, F>(init_fn: F) -> UseStatePtrEqHandle<T>
97where
98    T: 'static,
99    F: FnOnce() -> T,
100{
101    let handle = use_reducer_eq(move || UseStatePtrEqReducer {
102        value: Rc::new(init_fn()),
103    });
104
105    UseStatePtrEqHandle { inner: handle }
106}