Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Micro State Management with React Hooks

You're reading from   Micro State Management with React Hooks Explore custom hooks libraries like Zustand, Jotai, and Valtio to manage global states

Arrow left icon
Product type Paperback
Published in Feb 2022
Publisher Packt
ISBN-13 9781801812375
Length 254 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Daishi Kato Daishi Kato
Author Profile Icon Daishi Kato
Daishi Kato
Arrow right icon
View More author details
Toc

Table of Contents (16) Chapters Close

Preface 1. Part 1: React Hooks and Micro State Management
2. Chapter 1: What Is Micro State Management with React Hooks? FREE CHAPTER 3. Part 2: Basic Approaches to the Global State
4. Chapter 2: Using Local and Global States 5. Chapter 3: Sharing Component State with Context 6. Chapter 4: Sharing Module State with Subscription 7. Chapter 5: Sharing Component State with Context and Subscription 8. Part 3: Library Implementations and Their Uses
9. Chapter 6: Introducing Global State Libraries 10. Chapter 7: Use Case Scenario 1 – Zustand 11. Chapter 8: Use Case Scenario 2 – Jotai 12. Chapter 9: Use Case Scenario 3 – Valtio 13. Chapter 10: Use Case Scenario 4 – React Tracked 14. Chapter 11: Similarities and Differences between Three Global State Libraries 15. Other Books You May Enjoy

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.

You have been reading a chapter from
Micro State Management with React Hooks
Published in: Feb 2022
Publisher: Packt
ISBN-13: 9781801812375
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime