Build Your Own React State Management Library in Under 40 Lines of Code - With Typescript Support
Have you ever wondered how react state management libraries are built? from solutions like redux, with a lot of boilerplate and a large bundle size to libraries like zustand or jotai that are much lighter and simpler. Today we'll build our own state management library and see the magic that happens behind the scenes.
Written by Yehonatan Paripsky. Check out the original article here.
Understanding useSyncExternalStore
React 18 introduced a new hook called useSyncExternalStore which allows React to sync to any external store.
useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?
Here's a breakdown of its parameters:
- subscribe receives a callback as a parameter, and subscribes the callback to the external store so that it is called when the store state changes, it needs to return an unsubscribe function.
- getSnapshot gets the current snapshot of the store, this snapshot must be a cached value as react compares this value on each render using
Object.is(getSnapshot(), oldSnapshot)
, providing a new value each time will cause an infinite loop. - getServerSnapshot (optional) allows us to return a snapshot when rendering on the server, which can be helpful in certain cases where the external store or subscription source can't run on the server or needs specific handling to run on the server.
Leveraging useSyncExternalStore, we can build a minimalist store tailored to our requirements.
Why not just use React context?
React Context is a feature in React that allows a component to pass down props to the entire component tree below it, which means that it can be used as a store and is a viable option.
React context requires some boilerplate:
Using Context a lot can lead to "Context Hell", where a lot of context providers are nested in the App component:
Moreover, using context can inadvertently trigger re-renders across the entire component tree, as demonstrated below:
Also, using an external store can allow us to more easily sync and react with external systems like HTTP requests, with the context you'll resort to using useEffect, while with an external store, you can just update the store directly and the change will take effect in the subscribing components.
Building our store
Let's delve into the implementation of our store. We'll start with a basic structure and gradually enhance it based on our requirements.
Subscribers are an array of listeners that our store will notify of every change in the store's state.
State is the store's state which we'll update when setState is called and then notify all of the store's subscribers of the update.
To use the store in react we'll create createUseStore which is a helper that wraps createStore and useSyncExternalStore in a convenient way:
Using the store
With our store in place, let's start by building a Counter component:
and render it three times in our app:
We now see three counters on our page, clicking on Increment only increments one of the counters:
Let's make these 3 counters use the same state using our store, first, we'll create useCountStore using the createUseStore helper that we've created before:
now let's use our useCountStore hook in our counter:
Now our 3 counters are synced up and all of them increment together:
Thanks to the use of generics, typescript knows that count is a number and setCount is a callback that accepts a number:
Next steps
Some ideas on how our simple store can be improved and built upon:
Reducing state
Setting state is pretty direct in our store, which is convenient but we sometimes might need to handle complex logic when determining our state, that's where a reducer might help us, we can add a new dispatch function to our store:
Handling deeply nested state
Setting a new state requires destructuring the existing state, which can be annoying if we have a deeply nested state, to solve that we can use Immer or a similar library:
We can even add Immer to our store internally, and accept a callback in setState like so:
Conclusion
In this tutorial, we went through the steps of building a simple React state management library with TypeScript support.
By leveraging React's useSyncExternalStore
hook, we built a simple yet powerful store that seamlessly integrates with React components.
Now that you've got the hang of it, you're all set to build your own tailor-made state management library.