PHPnews.io

Manage React State with zustand

Written by Bram.us / Original link on Dec. 2, 2019

zustand.png

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 →

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

tutorialzine daylerees elsewhere link redux state bram

« The Power of the JSON.stringify() replacer parameter - Building a Website Screenshot API with Puppeteer and Google Cloud Functions »