Back

Zustand

Zustand is a hook-based state management library for React, inspired by Flux, but more lightweight than Redux, and with less boilerplate than Context.

Examples

State sharing in sibling functional components

These are 2 independently defined functional components (i.e. 2 different functions in different files).

They both - separately from each other - instantiate the same zustand store, which has an integer value and functions to increment it and decrement it.

If you press the +/- buttons in either component, you will see that the state is automatically propagated from one to the other.

Basic zustand usage
-
0
+
Cross component
-
0
+

Splitting a large Zustand store up

As the state of the application grows, it may be helpful to compartmentalize the data in Zustand.

Zustand recommends using the Slices pattern, which is demonstrated in the example below.

Splitting up Zustand stores with the Slices pattern
  • This is an implementation of the Slices pattern, recommended by Zustand.
  • Instantiates useComboStore
  • That store is assembled from functions that can be defined across multiple files.
  • The counters below represent 2 different values in a compound store, and the third value is their sum.
  • With a naive implementation, the 2 basic values must know about their dependent values, and take responsibility for pushing updates to dependents.
-
0
+
+
-
1
+
=
-
1
+

Using Zustand state across stores

The problem with the example above is that data sources need to be aware of all their dependents, and update the dependents.

This makes it harder to develop modular data structures - since new modules require updating old modules.

It's possible to reverse the relationship - by subscribing to Zustand state changes explicitly from dependent stores. In this example, subscriptions are used to build a self-updating dependent Zustand store - liberating parent data sources from needing to know about dependent values.

Notice that the red value below matches the value at the top of the page: unlike useComboStore, this approach allows sharing state across unrelated stores that don't have direct access to each other's state (useSum and useCounter).

Sharing Zustand state across stores
  • Instantiates useSum
  • That store sums data from two other stores: useCounter and useOtherCounter
  • That's achieved by subscribing from the compound store to each of the lower level stores.
  • The first counter shares state with other examples on this page.
-
0
+
+
-
1
+
=
-
1
+