React Tapas 10: zustand
TL;DR: I recommend zustand for global state instead of React context (that, in turn, replaced redux)
Zustand allows to share global state (and business logic! thanks Carlos) between several components in a very easy way,
The library is very small, documentation is great (and home page beautiful), so go and take a look.
Create a store #
We pass a store creator function to zustand and it returns a hook:
import create from "zustand"
function createStore() {
return { status: "This is the status" }
}
const useStatus = create(createStore)
export default useStatus
This createStore function will receive as params a function to modify our status. We can use that function to add methods to the store:
function createStore(set) {
return {
status: "This is the status"
setStatus: (newStatus) => set({ status: newStatus });
}
}
With TS we need to add the types:
type StatusStore = {
status: string;
setStatus: (nesStatus: string) => void;
};
const useStatus = create<StatusStore>((set) => ({
thisIsAnotherThing: "whatever here",
status: "This is the status",
setStatus: (newStatus) => set({ status: newStatus }),
})
);
export default useStatus;
Usage #
This is a hook, so can be used like any other hook inside our components:
function StatusComponent() {
const { status } = useStatus();
return <div>{status}</div>
}
Worth mentioning #
- As Joseph said, global state is considered harmful. But 1) with Javascript, global state is safe (no race conditions) 2) we are good developers and use it with caution.
- The principal use case is authentication and authorization. But can be used to extract any shared logic (like hooks). It's also very useful to prevent prop drilling (thanks David!)
- zustand provides global state. React context allow shared state for some components of the component tree. Global state is just one specific case (shared state for all components)
- zustand includes two middlewares (called Decorators in OOP). Redux middleware allow to inspect your state in a development tool. The persist middleware stores the changes in the local storage (very handy for authorization, for example)
- zustand can be used to fix performance issues with the slices and subscribe features.