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

Adding a basic Subscription

Here, we'll learn about the Subscription mechanism and how to connect a module state to the React state.

Subscription is a way to get notified of things such as updates. A typical use of a Subscription would look like the following:

const unsubscribe = store.subscribe(() => {
  console.log('store is updated');

Here, we assume a store variable to have a subscribe method that takes a callback function and returns an unsubscribe function.

In this case, the expected behavior is that whenever store is updated, the callback function is invoked and it shows the console log.

Now, let's implement a module state with a Subscription. We'll call it store, which holds the state value and the subscribe method, in addition to the getState and setState methods that we described in the Exploring the module state section. A createStore is a function to create store with an initial state value:

type Store<T&gt...