dioxus_hooks/use_set_compare.rs
1use dioxus_core::use_hook;
2use dioxus_signals::{ReadSignal, SetCompare};
3use std::hash::Hash;
4
5/// Creates a new SetCompare which efficiently tracks when a value changes to check if it is equal to a set of values.
6///
7/// Generally, you shouldn't need to use this hook. Instead you can use [`crate::use_memo()`]. If you have many values that you need to compare to a single value, this hook will change updates from O(n) to O(1) where n is the number of values you are comparing to.
8///
9/// ```rust
10/// use dioxus::prelude::*;
11///
12/// fn App() -> Element {
13/// let mut count = use_signal(|| 0);
14/// let compare = use_set_compare(move || count());
15///
16/// rsx! {
17/// for i in 0..10 {
18/// // Child will only re-render when i == count
19/// Child { compare, i }
20/// }
21/// button {
22/// // This will only rerender the child with the old and new value of i == count
23/// // Because we are using a set compare, this will be O(1) instead of the O(n) performance of a selector
24/// onclick: move |_| count += 1,
25/// "Increment"
26/// }
27/// }
28/// }
29///
30/// #[component]
31/// fn Child(i: usize, compare: SetCompare<usize>) -> Element {
32/// let active = use_set_compare_equal(i, compare);
33/// if active() {
34/// rsx! { "Active" }
35/// } else {
36/// rsx! { "Inactive" }
37/// }
38/// }
39/// ```
40#[doc = include_str!("../docs/rules_of_hooks.md")]
41#[doc = include_str!("../docs/moving_state_around.md")]
42#[must_use]
43pub fn use_set_compare<R: Eq + Hash + 'static>(f: impl FnMut() -> R + 'static) -> SetCompare<R> {
44 use_hook(move || SetCompare::new(f))
45}
46
47/// A hook that returns true if the value is equal to the value in the set compare.
48#[doc = include_str!("../docs/rules_of_hooks.md")]
49#[doc = include_str!("../docs/moving_state_around.md")]
50#[must_use]
51pub fn use_set_compare_equal<R: Eq + Hash + 'static>(
52 value: R,
53 mut compare: SetCompare<R>,
54) -> ReadSignal<bool> {
55 use_hook(move || compare.equal(value))
56}