Usage
When you want to create a signal within the React render context which triggers re-renders.
There are two ways to read a signal from useSignal:
- Using the non-accessor value
- Combining the
AccessorwithReactiveTextfor fine-grained reactivity
Basic State
useSignal is a more reliable version of useState that includes an additional Accessor as the third Tuple item.
Reading State
There are two ways to read the signal value based on your preferred method:
- Using the first value: the latest accessor result
- Using the third value: the pure accessor function
Both options are valid and more performant than native React state. However, only
the pure accessor can be passed into ReactiveText.
Setting State
With Cerberus Signals, how you set the state no longer matters. You are free to use mutation or immutability. Both results will yield the same high performant and reliable reactivity.
The second value of the Tuple is the Setter function.
The setter API is the exact same as the createSignal Setter and accepts any type
of setting value or callback.
useSignal vs. useState: The "Stale Closure" Killer
React's useState traps values in closures. This is the root cause of 90% of React bugs. If you use useState inside a setInterval, an event listener, or an async fetch block, it will read the old, stale value from when the component first rendered.
To fix it, you have to juggle useRef and complex useEffect dependency arrays.
useSignal completely destroys this problem because it returns a getter Accessor function as the third option in the Tuple:
Separation of State and Lifecycle
With useState, the state is glued to the component. If the component unmounts, the state dies.
With useSignal, the state lives in the external reactive graph, and useRead just "peeks" at it. This means you can trigger complex business logic (createEffect, createComputed) completely outside of React's render cycle.
If setLocal updates the signal, it instantly triggers any pure-JS createEffect you have listening to it, synchronously, before React even begins its slow VDOM render phase.
API
useSignal accepts the following options:
| Params | Required | Description |
|---|---|---|
initialValue | false | The initial value to set for the accessor. |
Return
useSignal returns a SignalTuple<T> Array of the following values:
| Index | Type | Description |
|---|---|---|
| 0 | T | The latest value of the accessor. |
| 1 | Setter<T> | A function to update the signal value. |
| 2 | Accessor<T> | A function that returns the latest value when called. |