Table Of Contents
I’ve been explaining how libraries like Jotai work fairly often recently. They provide a “signal-like” experience in React by exposing “subscribe-able” state. Jotai calls it “atoms”. You can call it whatever.
#Signal-based Global State
The pattern is this.
When calling setUsername
in any component, it will update all components that make use of username
. A call of setUsername
in our UserPanel
component will also update the username
in our UserIcon
component.
How?
With a hidden mapping of signal objects to a list of setState
functions.
#The Library
It may be clearer with this stripped-down example of the implementation.
When we call our local setState
, we’re actually calling all setState
functions from anyone that is also using this signal. The setState
it calls will update the component that is using this signal.
For this to actually be useful, however, we’ll need to actually map our signal object to its own setStateFuncs
list, making our full code look more like this.
Because our “signal objects” just need to be an object with a value property, they can be defined as simply as:
The full code (with some minor tweaks) is available as a github gist here.
# end note