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
Published 3 years ago
Updated 3 years ago

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.

egghead
egghead
~ 2 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today