Manage React State with zustand

Small, fast and scaleable bearbones state-management solution. Has a comfy api based on hooks, that isn’t boilerplatey or opinionated, but still just enough to be explicit and flux-like.

import create from 'zustand'

const [useStore] = create(set => ({
  count: 1,
  inc: () => set(state => ({ count: state.count + 1 })),
  dec: () => set(state => ({ count: state.count - 1 })),
}))

function Counter() {
  const { count, inc, dec } = useStore()
  return (
    <>
      <h1>{count}</h1>
      <button onClick={inc}>up</button>
      <button onClick={dec}>down</button>
    </>
  )
}

Here’s where things get interesting: To use parts of the store in child components, call the useStore hook, selecting the piece you need from it — no providers needed:

function Counter() {
  const count = useStore(state => state.count)
  return <h1>{count}</h1>
}

Installation per NPM/Yarn:

npm install zustand

Zustand – Bear necessities for state management in React →

🌐 In case you don’t get the name: Zustand is German for State.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.