Introduzione a Zustand
Perché un’altra libreria di stato?
Redux è potente ma verboso (actions, reducers, thunks, providers). Context API è semplice ma ha problemi di performance (re-renderizza tutto l’albero se non ottimizzato).
Zustand (tedesco per “stato”) risolve tutto:
- Semplicità: Definisci uno store come un hook.
- Zero Boilerplate: Niente providers da avvolgere nell’App.
- Selettivo: I componenti si ri-renderizzano SOLO quando cambia la fetta di stato che stanno ascoltando.
- Agnostico: Può essere usato anche fuori dai componenti React.
Installazione
```bash npm install zustand ```
Esempio Rapido
```tsx import { create } from ‘zustand’
const useStore = create((set) => ({ bears: 0, increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), removeAllBears: () => set({ bears: 0 }), }))
function BearCounter() { const bears = useStore((state) => state.bears) return
{bears} around here …
}function Controls() { const increasePopulation = useStore((state) => state.increasePopulation) return } ```