dioxus_signals/
signal.rs

1use crate::{
2    default_impl, fmt_impls, read::*, write::*, write_impls, CopyValue, Global, GlobalMemo,
3    GlobalSignal, Memo, ReadableRef, WritableRef,
4};
5use dioxus_core::{IntoAttributeValue, IntoDynNode, ReactiveContext, ScopeId, Subscribers};
6use generational_box::{BorrowResult, Storage, SyncStorage, UnsyncStorage};
7use std::{collections::HashSet, ops::Deref, sync::Arc, sync::Mutex};
8
9#[doc = include_str!("../docs/signals.md")]
10#[doc(alias = "State")]
11#[doc(alias = "UseState")]
12#[doc(alias = "UseRef")]
13pub struct Signal<T, S: 'static = UnsyncStorage> {
14    pub(crate) inner: CopyValue<SignalData<T>, S>,
15}
16
17/// A signal that can safely shared between threads.
18#[doc(alias = "SendSignal")]
19#[doc(alias = "UseRwLock")]
20#[doc(alias = "UseRw")]
21#[doc(alias = "UseMutex")]
22pub type SyncSignal<T> = Signal<T, SyncStorage>;
23
24/// The data stored for tracking in a signal.
25pub struct SignalData<T> {
26    pub(crate) subscribers: Arc<Mutex<HashSet<ReactiveContext>>>,
27    pub(crate) value: T,
28}
29
30impl<T: 'static> Signal<T> {
31    /// Creates a new [`Signal`]. Signals are a Copy state management solution with automatic dependency tracking.
32    ///
33    /// <div class="warning">
34    ///
35    /// This function should generally only be called inside hooks. The signal that this function creates is owned by the current component and will only be dropped when the component is dropped. If you call this function outside of a hook many times, you will leak memory until the component is dropped.
36    ///
37    /// ```rust
38    /// # use dioxus::prelude::*;
39    /// fn MyComponent() {
40    ///     // ❌ Every time MyComponent runs, it will create a new signal that is only dropped when MyComponent is dropped
41    ///     let signal = Signal::new(0);
42    ///     use_context_provider(|| signal);
43    ///     // ✅ Since the use_context_provider hook only runs when the component is created, the signal will only be created once and it will be dropped when MyComponent is dropped
44    ///     let signal = use_context_provider(|| Signal::new(0));
45    /// }
46    /// ```
47    ///
48    /// </div>
49    #[track_caller]
50    pub fn new(value: T) -> Self {
51        Self::new_maybe_sync(value)
52    }
53
54    /// Create a new signal with a custom owner scope. The signal will be dropped when the owner scope is dropped instead of the current scope.
55    #[track_caller]
56    pub fn new_in_scope(value: T, owner: ScopeId) -> Self {
57        Self::new_maybe_sync_in_scope(value, owner)
58    }
59
60    /// Creates a new [`GlobalSignal`] that can be used anywhere inside your dioxus app. This signal will automatically be created once per app the first time you use it.
61    ///
62    /// # Example
63    /// ```rust, no_run
64    /// # use dioxus::prelude::*;
65    /// // Create a new global signal that can be used anywhere in your app
66    /// static SIGNAL: GlobalSignal<i32> = Signal::global(|| 0);
67    ///
68    /// fn App() -> Element {
69    ///     rsx! {
70    ///         button {
71    ///             onclick: move |_| *SIGNAL.write() += 1,
72    ///             "{SIGNAL}"
73    ///         }
74    ///     }
75    /// }
76    /// ```
77    ///
78    /// <div class="warning">
79    ///
80    /// Global signals are generally not recommended for use in libraries because it makes it more difficult to allow multiple instances of components you define in your library.
81    ///
82    /// </div>
83    #[track_caller]
84    pub const fn global(constructor: fn() -> T) -> GlobalSignal<T> {
85        Global::new(constructor)
86    }
87}
88
89impl<T: PartialEq + 'static> Signal<T> {
90    /// Creates a new [`GlobalMemo`] that can be used anywhere inside your dioxus app. This memo will automatically be created once per app the first time you use it.
91    ///
92    /// # Example
93    /// ```rust, no_run
94    /// # use dioxus::prelude::*;
95    /// static SIGNAL: GlobalSignal<i32> = Signal::global(|| 0);
96    /// // Create a new global memo that can be used anywhere in your app
97    /// static DOUBLED: GlobalMemo<i32> = Signal::global_memo(|| SIGNAL() * 2);
98    ///
99    /// fn App() -> Element {
100    ///     rsx! {
101    ///         button {
102    ///             // When SIGNAL changes, the memo will update because the SIGNAL is read inside DOUBLED
103    ///             onclick: move |_| *SIGNAL.write() += 1,
104    ///             "{DOUBLED}"
105    ///         }
106    ///     }
107    /// }
108    /// ```
109    ///
110    /// <div class="warning">
111    ///
112    /// Global memos are generally not recommended for use in libraries because it makes it more difficult to allow multiple instances of components you define in your library.
113    ///
114    /// </div>
115    #[track_caller]
116    pub const fn global_memo(constructor: fn() -> T) -> GlobalMemo<T>
117    where
118        T: PartialEq,
119    {
120        GlobalMemo::new(constructor)
121    }
122
123    /// Creates a new unsync Selector. The selector will be run immediately and whenever any signal it reads changes.
124    ///
125    /// Selectors can be used to efficiently compute derived data from signals.
126    #[track_caller]
127    pub fn memo(f: impl FnMut() -> T + 'static) -> Memo<T> {
128        Memo::new(f)
129    }
130
131    /// Creates a new unsync Selector with an explicit location. The selector will be run immediately and whenever any signal it reads changes.
132    ///
133    /// Selectors can be used to efficiently compute derived data from signals.
134    pub fn memo_with_location(
135        f: impl FnMut() -> T + 'static,
136        location: &'static std::panic::Location<'static>,
137    ) -> Memo<T> {
138        Memo::new_with_location(f, location)
139    }
140}
141
142impl<T, S: Storage<SignalData<T>>> Signal<T, S> {
143    /// Creates a new Signal. Signals are a Copy state management solution with automatic dependency tracking.
144    #[track_caller]
145    #[tracing::instrument(skip(value))]
146    pub fn new_maybe_sync(value: T) -> Self
147    where
148        T: 'static,
149    {
150        Self {
151            inner: CopyValue::<SignalData<T>, S>::new_maybe_sync(SignalData {
152                subscribers: Default::default(),
153                value,
154            }),
155        }
156    }
157
158    /// Creates a new Signal with an explicit caller. Signals are a Copy state management solution with automatic dependency tracking.
159    ///
160    /// This method can be used to provide the correct caller information for signals that are created in closures:
161    ///
162    /// ```rust
163    /// # use dioxus::prelude::*;
164    /// #[track_caller]
165    /// fn use_my_signal(function: impl FnOnce() -> i32) -> Signal<i32> {
166    ///     // We capture the caller information outside of the closure so that it points to the caller of use_my_custom_hook instead of the closure
167    ///     let caller = std::panic::Location::caller();
168    ///     use_hook(move || Signal::new_with_caller(function(), caller))
169    /// }
170    /// ```
171    pub fn new_with_caller(value: T, caller: &'static std::panic::Location<'static>) -> Self
172    where
173        T: 'static,
174    {
175        Self {
176            inner: CopyValue::new_with_caller(
177                SignalData {
178                    subscribers: Default::default(),
179                    value,
180                },
181                caller,
182            ),
183        }
184    }
185
186    /// Create a new Signal without an owner. This will leak memory if you don't manually drop it.
187    pub fn leak_with_caller(value: T, caller: &'static std::panic::Location<'static>) -> Self
188    where
189        T: 'static,
190    {
191        Self {
192            inner: CopyValue::leak_with_caller(
193                SignalData {
194                    subscribers: Default::default(),
195                    value,
196                },
197                caller,
198            ),
199        }
200    }
201
202    /// Create a new signal with a custom owner scope. The signal will be dropped when the owner scope is dropped instead of the current scope.
203    #[track_caller]
204    #[tracing::instrument(skip(value))]
205    pub fn new_maybe_sync_in_scope(value: T, owner: ScopeId) -> Self {
206        Self::new_maybe_sync_in_scope_with_caller(value, owner, std::panic::Location::caller())
207    }
208
209    /// Create a new signal with a custom owner scope and a custom caller. The signal will be dropped when the owner scope is dropped instead of the current scope.
210    #[tracing::instrument(skip(value))]
211    pub fn new_maybe_sync_in_scope_with_caller(
212        value: T,
213        owner: ScopeId,
214        caller: &'static std::panic::Location<'static>,
215    ) -> Self {
216        Self {
217            inner: CopyValue::<SignalData<T>, S>::new_maybe_sync_in_scope_with_caller(
218                SignalData {
219                    subscribers: Default::default(),
220                    value,
221                },
222                owner,
223                caller,
224            ),
225        }
226    }
227
228    /// Point to another signal. This will subscribe the other signal to all subscribers of this signal.
229    pub fn point_to(&self, other: Self) -> BorrowResult
230    where
231        T: 'static,
232    {
233        #[allow(clippy::mutable_key_type)]
234        let this_subscribers = self.inner.value.read().subscribers.lock().unwrap().clone();
235        let other_read = other.inner.value.read();
236        for subscriber in this_subscribers.iter() {
237            subscriber.subscribe(other_read.subscribers.clone());
238        }
239        self.inner.point_to(other.inner)
240    }
241
242    /// Drop the value out of the signal, invalidating the signal in the process.
243    pub fn manually_drop(&self)
244    where
245        T: 'static,
246    {
247        self.inner.manually_drop()
248    }
249
250    /// Get the scope the signal was created in.
251    pub fn origin_scope(&self) -> ScopeId {
252        self.inner.origin_scope()
253    }
254
255    fn update_subscribers(&self)
256    where
257        T: 'static,
258    {
259        {
260            let inner = self.inner.read();
261
262            // We cannot hold the subscribers lock while calling mark_dirty, because mark_dirty can run user code which may cause a new subscriber to be added. If we hold the lock, we will deadlock.
263            #[allow(clippy::mutable_key_type)]
264            let mut subscribers = std::mem::take(&mut *inner.subscribers.lock().unwrap());
265            subscribers.retain(|reactive_context| reactive_context.mark_dirty());
266            // Extend the subscribers list instead of overwriting it in case a subscriber is added while reactive contexts are marked dirty
267            inner.subscribers.lock().unwrap().extend(subscribers);
268        }
269    }
270
271    /// Get the generational id of the signal.
272    pub fn id(&self) -> generational_box::GenerationalBoxId {
273        self.inner.id()
274    }
275
276    /// **This pattern is no longer recommended. Prefer [`peek`](ReadableExt::peek) or creating new signals instead.**
277    ///
278    /// This function is the equivalent of the [write_silent](https://docs.rs/dioxus/latest/dioxus/prelude/struct.UseRef.html#method.write_silent) method on use_ref.
279    ///
280    /// ## What you should use instead
281    ///
282    /// ### Reading and Writing to data in the same scope
283    ///
284    /// Reading and writing to the same signal in the same scope will cause that scope to rerun forever:
285    /// ```rust, no_run
286    /// # use dioxus::prelude::*;
287    /// let mut signal = use_signal(|| 0);
288    /// // This makes the scope rerun whenever we write to the signal
289    /// println!("{}", *signal.read());
290    /// // This will rerun the scope because we read the signal earlier in the same scope
291    /// *signal.write() += 1;
292    /// ```
293    ///
294    /// You may have used the write_silent method to avoid this infinite loop with use_ref like this:
295    /// ```rust, no_run
296    /// # use dioxus::prelude::*;
297    /// let signal = use_signal(|| 0);
298    /// // This makes the scope rerun whenever we write to the signal
299    /// println!("{}", *signal.read());
300    /// // Write silent will not rerun any subscribers
301    /// *signal.write_silent() += 1;
302    /// ```
303    ///
304    /// Instead you can use the [`peek`](ReadableExt::peek) and [`write`](WritableExt::write) methods instead. The peek method will not subscribe to the current scope which will avoid an infinite loop if you are reading and writing to the same signal in the same scope.
305    /// ```rust, no_run
306    /// # use dioxus::prelude::*;
307    /// let mut signal = use_signal(|| 0);
308    /// // Peek will read the value but not subscribe to the current scope
309    /// println!("{}", *signal.peek());
310    /// // Write will update any subscribers which does not include the current scope
311    /// *signal.write() += 1;
312    /// ```
313    ///
314    /// ### Reading and Writing to different data
315    ///
316    ///
317    ///
318    /// ## Why is this pattern no longer recommended?
319    ///
320    /// This pattern is no longer recommended because it is very easy to allow your state and UI to grow out of sync. `write_silent` globally opts out of automatic state updates which can be difficult to reason about.
321    ///
322    ///
323    /// Lets take a look at an example:
324    /// main.rs:
325    /// ```rust, no_run
326    /// # use dioxus::prelude::*;
327    /// # fn Child() -> Element { unimplemented!() }
328    /// fn app() -> Element {
329    ///     let signal = use_context_provider(|| Signal::new(0));
330    ///
331    ///     // We want to log the value of the signal whenever the app component reruns
332    ///     println!("{}", *signal.read());
333    ///
334    ///     rsx! {
335    ///         button {
336    ///             // If we don't want to rerun the app component when the button is clicked, we can use write_silent
337    ///             onclick: move |_| *signal.write_silent() += 1,
338    ///             "Increment"
339    ///         }
340    ///         Child {}
341    ///     }
342    /// }
343    /// ```
344    /// child.rs:
345    /// ```rust, no_run
346    /// # use dioxus::prelude::*;
347    /// fn Child() -> Element {
348    ///     let signal: Signal<i32> = use_context();
349    ///
350    ///     // It is difficult to tell that changing the button to use write_silent in the main.rs file will cause UI to be out of sync in a completely different file
351    ///     rsx! {
352    ///         "{signal}"
353    ///     }
354    /// }
355    /// ```
356    ///
357    /// Instead [`peek`](ReadableExt::peek) locally opts out of automatic state updates explicitly for a specific read which is easier to reason about.
358    ///
359    /// Here is the same example using peek:
360    /// main.rs:
361    /// ```rust, no_run
362    /// # use dioxus::prelude::*;
363    /// # fn Child() -> Element { unimplemented!() }
364    /// fn app() -> Element {
365    ///     let mut signal = use_context_provider(|| Signal::new(0));
366    ///
367    ///     // We want to log the value of the signal whenever the app component reruns, but we don't want to rerun the app component when the signal is updated so we use peek instead of read
368    ///     println!("{}", *signal.peek());
369    ///
370    ///     rsx! {
371    ///         button {
372    ///             // We can use write like normal and update the child component automatically
373    ///             onclick: move |_| *signal.write() += 1,
374    ///             "Increment"
375    ///         }
376    ///         Child {}
377    ///     }
378    /// }
379    /// ```
380    /// child.rs:
381    /// ```rust, no_run
382    /// # use dioxus::prelude::*;
383    /// fn Child() -> Element {
384    ///     let signal: Signal<i32> = use_context();
385    ///
386    ///     rsx! {
387    ///         "{signal}"
388    ///     }
389    /// }
390    /// ```
391    #[track_caller]
392    #[deprecated = "This pattern is no longer recommended. Prefer `peek` or creating new signals instead."]
393    pub fn write_silent(&self) -> WriteLock<'static, T, S> {
394        WriteLock::map(self.inner.write_unchecked(), |inner: &mut SignalData<T>| {
395            &mut inner.value
396        })
397    }
398}
399
400impl<T, S: Storage<SignalData<T>>> Readable for Signal<T, S> {
401    type Target = T;
402    type Storage = S;
403
404    #[track_caller]
405    fn try_read_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>>
406    where
407        T: 'static,
408    {
409        let inner = self.inner.try_read_unchecked()?;
410
411        if let Some(reactive_context) = ReactiveContext::current() {
412            tracing::trace!("Subscribing to the reactive context {}", reactive_context);
413            reactive_context.subscribe(inner.subscribers.clone());
414        }
415
416        Ok(S::map(inner, |v| &v.value))
417    }
418
419    /// Get the current value of the signal. **Unlike read, this will not subscribe the current scope to the signal which can cause parts of your UI to not update.**
420    ///
421    /// If the signal has been dropped, this will panic.
422    #[track_caller]
423    fn try_peek_unchecked(&self) -> BorrowResult<ReadableRef<'static, Self>>
424    where
425        T: 'static,
426    {
427        self.inner
428            .try_read_unchecked()
429            .map(|inner| S::map(inner, |v| &v.value))
430    }
431
432    fn subscribers(&self) -> Subscribers
433    where
434        T: 'static,
435    {
436        self.inner.read().subscribers.clone().into()
437    }
438}
439
440impl<T: 'static, S: Storage<SignalData<T>>> Writable for Signal<T, S> {
441    type WriteMetadata = SignalSubscriberDrop<T, S>;
442
443    #[track_caller]
444    fn try_write_unchecked(
445        &self,
446    ) -> Result<WritableRef<'static, Self>, generational_box::BorrowMutError> {
447        #[cfg(debug_assertions)]
448        let origin = std::panic::Location::caller();
449        self.inner.try_write_unchecked().map(|inner| {
450            let borrow = S::map_mut(inner.into_inner(), |v| &mut v.value);
451            WriteLock::new_with_metadata(
452                borrow,
453                SignalSubscriberDrop {
454                    signal: *self,
455                    #[cfg(debug_assertions)]
456                    origin,
457                },
458            )
459        })
460    }
461}
462
463impl<T> IntoAttributeValue for Signal<T>
464where
465    T: Clone + IntoAttributeValue + 'static,
466{
467    fn into_value(self) -> dioxus_core::AttributeValue {
468        self.with(|f| f.clone().into_value())
469    }
470}
471
472impl<T> IntoDynNode for Signal<T>
473where
474    T: Clone + IntoDynNode + 'static,
475{
476    fn into_dyn_node(self) -> dioxus_core::DynamicNode {
477        self().into_dyn_node()
478    }
479}
480
481impl<T, S: Storage<SignalData<T>>> PartialEq for Signal<T, S> {
482    fn eq(&self, other: &Self) -> bool {
483        self.inner == other.inner
484    }
485}
486
487impl<T, S: Storage<SignalData<T>>> Eq for Signal<T, S> {}
488
489/// Allow calling a signal with signal() syntax
490///
491/// Currently only limited to copy types, though could probably specialize for string/arc/rc
492impl<T: Clone + 'static, S: Storage<SignalData<T>> + 'static> Deref for Signal<T, S> {
493    type Target = dyn Fn() -> T;
494
495    fn deref(&self) -> &Self::Target {
496        unsafe { ReadableExt::deref_impl(self) }
497    }
498}
499
500#[cfg(feature = "serialize")]
501impl<T: serde::Serialize + 'static, Store: Storage<SignalData<T>> + 'static> serde::Serialize
502    for Signal<T, Store>
503{
504    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
505        self.read().serialize(serializer)
506    }
507}
508
509#[cfg(feature = "serialize")]
510impl<'de, T: serde::Deserialize<'de> + 'static, Store: Storage<SignalData<T>> + 'static>
511    serde::Deserialize<'de> for Signal<T, Store>
512{
513    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
514        Ok(Self::new_maybe_sync(T::deserialize(deserializer)?))
515    }
516}
517
518#[doc(hidden)]
519/// A drop guard that will update the subscribers of the signal when it is dropped.
520pub struct SignalSubscriberDrop<T: 'static, S: Storage<SignalData<T>> + 'static> {
521    signal: Signal<T, S>,
522    #[cfg(debug_assertions)]
523    origin: &'static std::panic::Location<'static>,
524}
525
526#[allow(clippy::no_effect)]
527impl<T: 'static, S: Storage<SignalData<T>> + 'static> Drop for SignalSubscriberDrop<T, S> {
528    fn drop(&mut self) {
529        #[cfg(debug_assertions)]
530        {
531            tracing::trace!(
532                "Write on signal at {} finished, updating subscribers",
533                self.origin
534            );
535        }
536        self.signal.update_subscribers();
537    }
538}
539
540fmt_impls!(Signal<T, S: Storage<SignalData<T>>>);
541default_impl!(Signal<T, S: Storage<SignalData<T>>>);
542write_impls!(Signal<T, S: Storage<SignalData<T>>>);
543
544impl<T, S> Clone for Signal<T, S> {
545    fn clone(&self) -> Self {
546        *self
547    }
548}
549
550impl<T, S> Copy for Signal<T, S> {}