Zustand is a fast, scalable, and minimal state management library for React. It’s simpler than Redux and works well with small to medium-sized applications. It provides a clean and straightforward API also does not requires any boilerplate to implememt Zustand. It can be used both inside and outside of React components.
There are some advantage on Zustand over redux.
- A minimal API with no boilerplate
- Global store without the need for React Context
- First-class TypeScript support
- Middleware support
Step-by-Step: Using Zustand in a React App
1. Install Zustand
Install Zustand with npm or yarn:
npm install zustand
or
yarn add zustand
2. Create a Typed Store
Let’s create a simple counter store with TypeScript types.
// src/store/useCounterStore.ts
import { create } from 'zustand';
interface CounterState {
count: number;
increase: () => void;
decrease: () => void;
reset: () => void;
}
const useCounterStore = create<CounterState>((set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
decrease: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
}));
export default useCounterStore;
3. Use the Store in a Component
Now, let’s use this store inside a React component.
// src/components/Counter.tsx
import React from 'react';
import useCounterStore from '../store/useCounterStore';
const Counter: React.FC = () => {
const { count, increase, decrease, reset } = useCounterStore();
return (
<div style={{ textAlign: 'center' }}>
<h2>Count: {count}</h2>
<button onClick={increase}>+</button>
<button onClick={decrease}>-</button>
<button onClick={reset}>Reset</button>
</div>
);
};
export default Counter;
4. Add the Component to Your App
Use the counter component in your main App.tsx file:
// src/App.tsx
import React from 'react';
import Counter from './components/Counter';
const App: React.FC = () => {
return (
<div>
<h1>Zustand + TypeScript Example</h1>
<Counter />
</div>
);
};
export default App;
Persist State with Middleware
You can persist store values to localStorage using zustand/middleware.
// src/store/useAuthStore.ts
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
interface AuthState {
token: string | null;
setToken: (token: string) => void;
logout: () => void;
}
const useAuthStore = create<AuthState>()(
persist(
(set) => ({
token: null,
setToken: (token) => set({ token }),
logout: () => set({ token: null }),
}),
{
name: 'auth-storage', // key in localStorage
}
)
);
export default useAuthStore;
Zustand is a powerful and minimal solution for managing global state in React till now. With the support of TypeScript it likes out of the box and it’s ideal for modern applications where simplicity, scalability, and strong typing are needed.
Top comments (0)