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)
1
Part 1: React Hooks and Micro State Management
3
Part 2: Basic Approaches to the Global State
8
Part 3: Library Implementations and Their Uses

Working with hooks

React hooks are essential for micro statement management. React hooks include some primitive hooks to implement state management solutions, such as the following:

  • The useState hook is a basic function to create a local state. Thanks to React hooks' composability, we can create a custom hook that can add various features based on useState.
  • The useReducer hook can create a local state too and is often used as a replacement for useState. We will revisit these hooks to learn about the similarities and differences between useState and useReducer later in this chapter.
  • The useEffect hook allows us to run logic outside the React render process. It's especially important to develop a state management library for a global state because it allows us to implement features that work with the React component lifecycle.

The reason why React hooks are novel is that they allow you to extract logic out of UI components. For example, the following is a counter example of the simple usage of the useState hook:

const Component = () => {
  const [count, setCount] = useState(0);
  return (
    <div>
      {count}
      <button onClick={() => setCount((c) => c + 1)}>+1
      </button>
    </div>
  );
};

Now, let's see how we can extract logic. Using the same counter example, we will create a custom hook named useCount, as follows:

const useCount = () => {
  const [count, setCount] = useState(0);
  return [count, setCount];
};
const Component = () => {
  const [count, setCount] = useCount();
  return (
    <div>
      {count}
      <button onClick={() => setCount((c) => c + 1)}>
        +1
      </button>
    </div>
  );
};

It doesn't change a lot, and some of you may think this is overcomplicated. However, there are two points to note, as follows:

  • We now have a clearer name—useCount.
  • Component is independent of the implementation of useCount.

The first point is very important for programming in general. If we name the custom hook properly, the code is more readable. Instead of useCount, you could name it useScore, usePercentage, or usePrice. Even though they have the same implementations, if the name is different, we consider it a different hook. Naming things is very important.

The second point is also important when it comes to micro state management libraries. As useCount is extracted from Component, we can add functionality without breaking the component.

For example, we want to output a debug message on the console when the count is changed. To do so, we would execute the following code:

const useCount = () => {
  const [count, setCount] = useState(0);
  useEffect(() => {
    console.log('count is changed to', count);
  }, [count]);
  return [count, setCount];
};

By just changing useCount, we can add a feature of showing a debug message. We do not need to change the component. This is the benefit of extracting logic as custom hooks.

We could also add a new rule. Suppose we don't want to allow the count to change arbitrarily, but only by increments of one. The following custom hook does the job:

const useCount = () => {
  const [count, setCount] = useState(0);
  const inc = () => setCount((c) => c + 1);
  return [count, inc];
};

This opens up the entire ecosystem to provide custom hooks for various purposes. They can be a wrapper to add a tiny functionality or a huge hook that has a larger job.

You will find many custom hooks publicly available on Node Package Manager (npm) (https://www.npmjs.com/search?q=react%20hooks) or GitHub (https://github.com/search?q=react+hooks&type=repositories).

We should also discuss a little about suspense and concurrent rendering, as React hooks are designed and developed to work with these modes.

Suspense for Data Fetching and Concurrent Rendering

Suspense for Data Fetching and Concurrent Rendering are not yet released by React, but it's important to mention them briefly.

Important Note

Suspense for Data Fetching and Concurrent Rendering may have different names when they are officially released, but these are the names at the time of writing.

Suspense for Data Fetching is a mechanism that basically allows you to code your components without worrying about async.

Concurrent Rendering is a mechanism to split the render process into chunks to avoid blocking the central processing unit (CPU) for long periods of time.

React hooks are designed to work with these mechanisms; however, you need to avoid misusing them.

For example, one rule is that you should not mutate an existing state object or ref object. Doing so may lead to unexpected behavior such as not triggering re-renders, triggering too many re-renders, and triggering partial re-renders (meaning some components re-render while others don't when they should).

Hook functions and component functions can be invoked multiple times. Hence, another rule is those functions have to be "pure" enough so that they behave consistently, even if they are invoked several times.

These are the two major rules people often violate. This is a hard problem in practice, because even if your code violates those rules, it may just work in Non-Concurrent Rendering. Hence, people wouldn't notice the misuse. Even in Concurrent Rendering, it may work to some extent without problems, and people would only see problems occasionally. This makes it especially difficult for beginners who are using React for the first time.

Unless you are familiar with these concepts, it's better to use well-designed and battle-tested (micro) state management libraries for future/newer versions of React.

Important Note

As of writing, Concurrent Rendering is described in the React 18 Working Group, which you can read about here: https://github.com/reactwg/react-18/discussions.

In this section, we revisited basic React hooks and got some understanding of the concepts. Coming up, we start exploring global states, which are the main topic in this book.