← Back
react react-tapas zustand

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 #