Build Your Own React State Management Library in Under 40 Lines of Code - With Typescript Support

Jun 17th, 2024
Build Your Own React State Management Library in Under 40 Lines of Code - With Typescript Support
URL Copied

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:

Screenshot 2024-06-17 at 14.47.12

Using Context a lot can lead to "Context Hell", where a lot of context providers are nested in the App component:

Screenshot 2024-06-17 at 14.47.55

Moreover, using context can inadvertently trigger re-renders across the entire component tree, as demonstrated below:

Screenshot 2024-06-17 at 14.48.19 
Using setCount from a consumer of the context will cause a re-render of the entire app (both Outer and Other will be re-rendered) because the state is set on the App component, and when it re-renders, all of its child components are also re-rendered.

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. 

Screenshot 2024-06-17 at 14.49.11

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:

Screenshot 2024-06-17 at 14.50.03

Using the store

With our store in place, let's start by building a Counter component:

Screenshot 2024-06-17 at 14.50.36

and render it three times in our app:

Screenshot 2024-06-17 at 14.50.56

We now see three counters on our page, clicking on Increment only increments one of the counters:
Counters starting point

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:

Screenshot 2024-06-17 at 14.52.02

now let's use our useCountStore hook in our counter: 

Screenshot 2024-06-17 at 14.52.23

Now our 3 counters are synced up and all of them increment together:

The 3 counters now share the same state

Thanks to the use of generics, typescript knows that count is a number and setCount is a callback that accepts a number:

Typescript support for the state

Typescript support for setState

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:

Screenshot 2024-06-17 at 14.54.13

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:

Screenshot 2024-06-17 at 14.55.22

We can even add Immer to our store internally, and accept a callback in setState like so:

 Screenshot 2024-06-17 at 14.55.45

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.

 

Main topics