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

The pros and cons of this approach

We have seen how Valtio works and one question is when we should use it and when we should not.

One big aspect is the mental model. We have two state-updating models. One is for immutable updates and the other for mutable updates. While JavaScript itself allows mutable updates, React is built around immutable states. Hence, if we mix the two models, we should be careful not to confuse ourselves. One possible solution would be to clearly separate the Valtio state and React state so that the mental model switch is reasonable. If it works, Valtio can fit in. Otherwise, maybe stick with immutable updates.

The major benefit of mutable updates is we can use native JavaScript functions.

For example, removing an item from an array with an index value can be written as follows:

array.splice(index, 1)

In immutable updates, this is not so easy. For example, it can be written with slice, as follows:

[...array.slice(0, index), ...array.slice...