00
:
00
:
00
:
00
Corso SEO AI - Usa SEOEMAIL al checkout per il 30% di sconto

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:

  1. Semplicità: Definisci uno store come un hook.
  2. Zero Boilerplate: Niente providers da avvolgere nell’App.
  3. Selettivo: I componenti si ri-renderizzano SOLO quando cambia la fetta di stato che stanno ascoltando.
  4. 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 } ```