Zustand is a hook-based state management library for React, inspired by Flux, but more lightweight than Redux, and with less boilerplate than Context.
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.
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.
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).