There are many cases where you want to share state between components in React. A lot of popular state management libraries implement this ‘module state’ for you such as Zustand.
We will implement a naive version of a createStore
function that allows you to share your state between components in React.
createStore
has a few functions that we return from it: getState
, setState
, and subscribe
. Just like with React Hooks, we can get and set state within components. Because this is shared state, we need to give components a mechanism for updating when state changes in a separate component, that is where subscribe
comes in. With the combination of these 3 functions, we can display and update a shared value between multiple components in React.
A glimpse into how Jotai is implemented, perhaps?