Quick Start Guide: Installing and Using Zustand with pnpm
Zustand is a state management library that is lighter than Redux and simpler to use than the Context API. Here are the steps for adding Zustand to a project with pnpm.
1. Install Package with pnpm
Navigate to your project's root directory in the terminal and run the following command to install:
Bash
pnpm add zustand
2. Creating a Store
Zustand uses the create function to define a store. A key feature is that it can be used immediately without any Provider setup.
TYPESCRIPT
import { create } from 'zustand'
// Define types for State and Actions
interface CounterState {
count: number
increment: () => void
decrement: () => void
}
// Create and export the store
export const useCounterStore = create<CounterState>((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}))
3. Using in Components
Call the store inside your component like a Hook. If you pick only the values you need with a selector, the component re-renders only when those values change. Calling useCounterStore() with no argument subscribes to the whole store, so any change triggers a re-render.
React + TS
import { useCounterStore } from './store'
function CounterComponent() {
// Select each piece of state and each function
const count = useCounterStore((state) => state.count)
const increment = useCounterStore((state) => state.increment)
const decrement = useCounterStore((state) => state.decrement)
return (
<div>
<h1>Value: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
)
}
4. Key Summary
- Zero Config: No need for Context Providers or complex initial boilerplate.
- Simple API: Update state via the
setfunction and consume it as a Hook in components. - Selectors: Subscribing only to the values you need cuts unnecessary re-renders.