Skip to main content

rok_ui_hooks/
lib.rs

1//! Fine-grained reactivity with a React-flavoured API.
2//!
3//! Components — if you write any — run **once**. Work is organised into effects,
4//! which re-run when the signals they read change, and memos, which recompute
5//! lazily when somebody reads them. No component tree is ever re-executed, so
6//! adding state never costs a re-render.
7//!
8//! ```
9//! use rok_ui_hooks::*;
10//!
11//! let (count, set_count) = use_state(0);
12//! let doubled = use_memo(
13//!     { let count = count.clone(); move || count.get() * 2 },
14//!     (),
15//! );
16//! let _effect = use_effect(
17//!     {
18//!         let (count, doubled) = (count.clone(), doubled.clone());
19//!         move || println!("count = {}, doubled = {}", count.get(), doubled.get())
20//!     },
21//!     (doubled,),
22//! );
23//!
24//! set_count.set(2); // count = 2, doubled = 4
25//! ```
26//!
27//! # The mental model
28//!
29//! The graph has three kinds of node, and the difference between them is the
30//! whole design:
31//!
32//! * **signals** hold a value. They have no dependencies. A write bumps a version
33//!   and *marks* what reads them.
34//! * **memos** are derived values. They are lazy: a marked memo recomputes when
35//!   somebody reads it, and its readers only wake up if the value really changed.
36//! * **effects** are side effects. They are eager: a marked effect is queued and
37//!   runs when the enclosing batch ends.
38//!
39//! A write runs nothing synchronously, which is what makes any graph shape
40//! glitch-free — see [`batch`], [`untrack`] and [`flush`] for the controls, and
41//! [`Root`] for scope.
42//!
43//! # Mapping to React and Solid
44//!
45//! | React                            | This crate                                            |
46//! |----------------------------------|-------------------------------------------------------|
47//! | `useState(v)`                    | [`use_state`] → `(ReadSignal, WriteSignal)`   |
48//! | `useEffect(fn, deps)`            | [`use_effect`] / [`use_effect_with`]                    |
49//! | `useMemo(fn, deps)`              | [`use_memo`] → [`Memo`]                                 |
50//! | `useReducer`                     | [`use_reducer`]                                        |
51//! | `useRef(v)`                      | [`use_ref`] → `Rc<RefCell<T>>`                          |
52//! | `useContext(ctx)`                | [`use_context`]                                        |
53//! | `createContext` / `<Provider>`    | [`create_context`] / [`with_provider`]                 |
54//! | Solid `createRoot`               | [`create_root`], [`Root`]                               |
55//! | Solid `createEffect`             | [`create_effect`]                                      |
56//! | Solid `createRenderEffect`       | [`create_render_effect`]                               |
57//! | `create()` + `useStore(s, sel)`   | [`create_store`] + [`use_store`]                        |
58//! | `createSelector`                 | [`Store::select`]                                      |
59//! | `createResource`                 | [`use_resource`]                                       |
60//! | `<For each={…}>`                 | [`create_keyed_list`]                                  |
61//! | `onCleanup(fn)`                  | [`on_cleanup`], [`use_cleanup`]                        |
62//!
63//! # Dependencies
64//!
65//! A `deps` argument is a tuple of **handles** and/or plain values; it is
66//! re-evaluated on every notification, so a handle contributes its current
67//! *value*:
68//!
69//! | deps        | meaning                                                       |
70//! |-------------|---------------------------------------------------------------|
71//! | `()`        | no declared deps: re-run when anything the body read changes    |
72//! | `(count,)`  | re-run only when `count` has a new value (React `[count]`)      |
73//! | `(0i32,)`   | constant: mount only (React `[]`)                               |
74//!
75//! # Features
76//!
77//! Everything above is core and always compiled: signals, memos, effects, deps,
78//! ownership, [`batch`], [`untrack`], [`flush`], [`use_reducer`],
79//! [`use_previous`] and [`OwnedRoot`]. The rest sits behind five features —
80//! **all of which are on by default**, so a plain dependency gets the whole
81//! surface and nothing changes for an existing user.
82//!
83//! | feature    | brings                                          | lives in              |
84//! |------------|-------------------------------------------------|-----------------------|
85//! | `store`    | [`create_store`], [`Store`], [`use_store`]     | `store.rs`            |
86//! | `context`  | [`create_context`], [`use_context`], [`with_provider`] | `context.rs`   |
87//! | `keyed`    | [`create_keyed_list`], [`KeyedList`]            | `keyed.rs`            |
88//! | `async`    | [`spawn`], [`Task`], [`use_resource`]           | `executor.rs`, `resource.rs` |
89//! | `timers`   | [`use_debounced`], [`use_throttled`]            | `timer.rs`, part of `hooks.rs` |
90//!
91//! Turn the default set off and ask for what you actually use:
92//!
93//! ```toml
94//! [dependencies]
95//! rok-ui-hooks = { version = "0.3", default-features = false, features = ["store", "async"] }
96//! ```
97//!
98//! `full` is an alias for all five, so `default = ["full"]` and
99//! `features = ["full"]` mean the same thing.
100//!
101//! Three consequences worth knowing before you trim:
102//!
103//! * [`tick`] compiles down to [`flush`] when `timers` and `async` are both off,
104//!   because there is then no deadline and no task to advance. It still exists,
105//!   so your loop does not need a conditional.
106//! * The provider machinery in `context.rs` stays compiled even with `context`
107//!   off. `runtime.rs` re-installs a captured provider stack on every run of
108//!   every node and that is not feature-dependent, so the feature removes the
109//!   public API, not the plumbing.
110//! * The `docs/*.md` files, the README and every example assume the default
111//!   features, because between them they cover the whole surface. Targets in
112//!   `Cargo.toml` declare `required-features`, so `cargo test
113//!   --no-default-features` skips them instead of failing.
114//!
115//! # Where to look next
116//!
117//! * `README.md` and `docs/getting-started.md` — the guided tour.
118//! * The `examples/` directory: `demo`, `advanced`, `todo_app`, `ownership`,
119//!   `keyed_list`, `async`, `context_demo`, `hooks_demo`, `store_demo`.
120//! * `docs/concepts.md` for the model, `docs/api-reference.md` for every item,
121//!   `docs/async-and-time.md` for the tick loop, `docs/patterns.md` for idioms
122//!   and pitfalls, `docs/architecture.md` for the internals, and
123//!   `docs/porting.md` for moving from React, Solid, or the 0.1 API.
124//! * Every code block in the README and `docs/` is compiled as a doctest, so the
125//!   documentation cannot drift from the code.
126
127#![forbid(unsafe_code)]
128#![warn(missing_docs)]
129
130mod context;
131mod deps;
132mod effect;
133#[cfg(feature = "async")]
134mod executor;
135mod hooks;
136#[cfg(feature = "keyed")]
137mod keyed;
138mod memo;
139#[cfg(feature = "async")]
140mod resource;
141mod runtime;
142mod signal;
143#[cfg(feature = "store")]
144mod store;
145#[cfg(feature = "timers")]
146mod timer;
147
148/// Compiles the code blocks in `README.md` as doctests. `cfg(doctest)` is set
149/// by rustdoc only, so this costs nothing in a normal build.
150#[cfg(doctest)]
151#[doc = include_str!("../README.md")]
152pub struct ReadmeDoctests;
153
154/// Compiles `docs/*.md` the same way: documentation that does not build is worse
155/// than no documentation.
156#[cfg(doctest)]
157mod markdown_doctests {
158    #[doc = include_str!("../docs/getting-started.md")]
159    pub struct GettingStarted;
160    #[doc = include_str!("../docs/concepts.md")]
161    pub struct Concepts;
162    #[doc = include_str!("../docs/api-reference.md")]
163    pub struct ApiReference;
164    #[doc = include_str!("../docs/async-and-time.md")]
165    pub struct AsyncAndTime;
166    #[doc = include_str!("../docs/patterns.md")]
167    pub struct Patterns;
168    #[doc = include_str!("../docs/architecture.md")]
169    pub struct Architecture;
170    #[doc = include_str!("../docs/porting.md")]
171    pub struct Porting;
172}
173
174#[cfg(feature = "context")]
175pub use context::{Context, create_context, use_context, with_provider};
176pub use deps::{DepItem, Deps};
177pub use effect::{
178    Effect, create_deferred_effect, create_effect, create_render_effect, use_cleanup, use_effect,
179    use_effect_with, use_ref,
180};
181#[cfg(feature = "async")]
182pub use executor::{Task, pending_tasks, spawn};
183#[cfg(feature = "timers")]
184pub use hooks::{Debounced, Throttled, use_debounced, use_throttled};
185pub use hooks::{Dispatch, OwnedRoot, create_owned_root, use_previous, use_reducer};
186#[cfg(feature = "keyed")]
187pub use keyed::{KeyedList, create_keyed_list};
188pub use memo::{Memo, create_memo, shallow_array_eq, shallow_vec_eq, use_memo, use_memo_eq};
189#[cfg(feature = "async")]
190pub use resource::{Resource, ResourceState, use_resource, use_resource_with};
191pub use runtime::{Root, batch, create_root, flush, on_cleanup, tick, untrack};
192pub use signal::{ReadSignal, WriteSignal, create_signal, use_state};
193#[cfg(feature = "store")]
194pub use store::{Store, Subscription, create_store, use_store};