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.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

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.