A small, fast and scalable state-management solution using simplified flux principles. Has a comfy api based on hooks
small
Zustand is one of the smallest state management libraries with a bundle size of just 1.13kb.fast
Zustand is fast, thanks to its small size, making us have instantaneous UI updates on changes to our state.scalable
With Zustand, we can create a store, which is a central point of truth where all our global app state resides in. Our store is simply a hook, which we can easily import and use where needed. making Zustand very scalable.
Let's go over a basic store example with Zustand using Typescript.
Step 0: Install zustand
yarn add zustand
Step 1: Import and Create your Store (ex: Authentication)
// authStore.ts
import create from 'zustand';
import getToken from './utils';
interface AuthStateType {
status: 'idle' | 'signOut' | 'signIn';
token: string | null;
signIn: (token: string) => void;
signOut: () => void;
hydrate: () => void;
}
export const useAuth = create<AuthStateType>((set, get) => ({
status: 'idle',
token: null,
signIn: token => {
set({ status: 'signIn', token: token });
},
signOut: () => {
set({ status: 'signOut', token: null });
},
hydrate: () => {
const token = getToken();
if (token !== null) {
get().signIn(token);
} else {
get().signOut();
}
},
}));
Step 2: Use your auth store (Inside of a React Component).
- Check status
const { status } = useAuth();
console.log(status); // idle
- SignIn
const { signIn, status } = useAuth();
signIn("user token");
console.log(status); // signIn
- SignOut
const { signOut, status } = useAuth();
signOut();
console.log(status); // signOut
- Hydrate
const { hydrate } = useAuth();
hydrate();
Step 3: Use your auth store (Outside of a React Component)
// authStore.ts
export const useAuth = create<AuthState>((set, get) => ({
...
}))
// add this line
export const hydrateAuth = () => useAuth.getState().hydrate();
now you can use hydrateAuth
Outside of a React Component.
import { hydrateAuth } from "./authStore.ts"
hydrateAuth()
Top comments (1)
Nice article, keep it up :-)