Book Image

Micro State Management with React Hooks

By : Daishi Kato
Book Image

Micro State Management with React Hooks

By: Daishi Kato

Overview of this book

State management is one of the most complex concepts in React. Traditionally, developers have used monolithic state management solutions. Thanks to React Hooks, micro state management is something tuned for moving your application from a monolith to a microservice. This book provides a hands-on approach to the implementation of micro state management that will have you up and running and productive in no time. You’ll learn basic patterns for state management in React and understand how to overcome the challenges encountered when you need to make the state global. Later chapters will show you how slicing a state into pieces is the way to overcome limitations. Using hooks, you'll see how you can easily reuse logic and have several solutions for specific domains, such as form state and server cache state. Finally, you'll explore how to use libraries such as Zustand, Jotai, and Valtio to organize state and manage development efficiently. By the end of this React book, you'll have learned how to choose the right global state management solution for your app requirement.
Table of Contents (16 chapters)
Part 1: React Hooks and Micro State Management
Part 2: Basic Approaches to the Global State
Part 3: Library Implementations and Their Uses

Working with a selector and useSubscription

The useStore hook we created in the previous section returns a whole state object. This means that any small part of the state object change will notify all useStore hooks and it can cause extra re-renders.

To avoid extra re-renders, we can introduce a selector to return the only part of the state that a component is interested in.

Let's first develop useStoreSelector.

We use the same createStore function defined in the previous section and create a store variable as follows:

const store = createStore({ count1: 0, count2: 0 });

The state in store has two counts – count1 and count2.

The useStoreSelector hook is similar to useStore, but it receives an additional selector function. It uses the selector function to scope the state:

const useStoreSelector = <T, S>(
  store: Store<T>,
  selector: (state: T) => S
) => {
  const [state, setState] =