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:
Accessor with ReactiveText for fine-grained reactivityuseSignal is a more reliable version of useState that includes an additional Accessor as the third Tuple item.
There are two ways to read the signal value based on your preferred method:
Both options are valid and more performant than native React state. However, only
the pure accessor can be passed into ReactiveText.
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" KillerReact'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:
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.
useSignal accepts the following options:
| Params | Required | Description |
|---|---|---|
initialValue | false | The initial value to set for the accessor. |
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. |
0
0Render Count: 1
0
0Render Count: 1
0
0Render Count: 1