Implementing Zustand: A More Streamlined Approach to State Management
Zustand (German for "state") is a popular state management library created by Daishi Kato. It offers a more streamlined approach compared to Redux, while following the same unidirectional model for managing state.
For this exercise, we'll use Zustand to manage our application state. To get started, copy the 03-cart-context-with-initial-state
directory and to a new 07-complete-zustand
directory.
My recommendation is to use two different stores for managing the state.
Specifically, we'll use two different Zustand state hooks: one for managing the cart and another for reviews.
Challenge
After installing zustand
, you'll need to remove the existing CartContext
and ReviewContext
objects and replace them each with their own Zustand store.
In case you aren't familiar with Zustand, here's a quick overview of how it works.
WARNING You cannot safely use Zustand hooks that are declared globally!
Zustand hooks are normally global, but you can also create a Zustand hook and pass it around in a context, like so:
In order to get the Zustand hook in a Client Component, follow this pattern:
From there you can call the hook like this:
The above could also be shortened to:
Zustand also allows you to use selectors like so:
The above will force a re-render only when the returned value from the selector changes.