Extract Module Logic (like Zustand) into a Custom React Hook

Daishi Kato
InstructorDaishi Kato
Share this video with your friends

Social Share Links

Send Tweet

We have two components that use the same store. They display the data and update the store when a button is clicked. The logic in each component is the same and can be extracted into a custom hook

In this lesson, we'll extract the store logic into a useStore hook and use that custom hook like you would any other React hook. Then we'll extend the behavior of the hook to accept a function to update the previous state value.

Daishi Kato: [0:02] We developed createStore to create a module state. It returns getState, setState, and subscribe functions. A store is created with a count property. Two components use the store and show the count. If you click the button, both numbers are incremented.

[0:20] Now, we want to extract the logic in the component with a custom hook. We name it useStore. useStore takes an argument, store.

[0:31] Let's handle in each case. Because useEffect is invoked afterward, there's a chance that the state is already changed. We can make sure to follow the change by calling the callback once in the effect.

[0:46] The useStore hook returns a tuple of state and setState function to update the store state. Using the useStore hook, we can simplify the Counter1 component. Do the same for the Counter2 component. We have the same behavior as before.

[1:07] This looks like useState, but there is a difference. setState should accept a function to update.

[1:13] Let's add the function update feature. In createStore, if the next state is a function, we call the function with the previous state. This allows the Counter1 component to use function update.

[1:32] In this lesson, we created useStore hook, which works like useState, but for module state.