zustand/docs/getting-started/introduction.mdx

54 lines
1.8 KiB
Plaintext

---
title: Introduction
description: How to use Zustand
nav: 0
---
⚠️ This doc is still under construction. https://github.com/pmndrs/zustand/discussions/1033
<p align="center">
<img width="600" src="https://github.com/pmndrs/zustand/raw/main/bear.jpg" />
</p>
A small, fast and scalable bearbones state-management solution. Has a comfy api based
on hooks, isn't boilerplatey or opinionated, but still just enough to be explicit
and flux-like.
Don't disregard it because it's cute. It has quite the claws, lots of time was spent to deal with common pitfalls, like the dreaded [zombie child problem](https://react-redux.js.org/api/hooks#stale-props-and-zombie-children), [react concurrency](https://github.com/bvaughn/rfcs/blob/useMutableSource/text/0000-use-mutable-source.md), and [context loss](https://github.com/facebook/react/issues/13332) between mixed renderers. It may be the one state-manager in the React space that gets all of these right.
You can try a live demo [here](https://codesandbox.io/s/dazzling-moon-itop4).
```bash
npm install zustand
```
## First create a store
Your store is a hook! You can put anything in it: primitives, objects, functions. The `set` function _merges_ state.
```jsx
import create from 'zustand'
const useStore = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}))
```
## Then bind your components, and that's it!
Use the hook anywhere, no providers needed. Select your state and the component will re-render on changes.
```jsx
function BearCounter() {
const bears = useStore((state) => state.bears)
return <h1>{bears} around here ...</h1>
}
function Controls() {
const increasePopulation = useStore((state) => state.increasePopulation)
return <button onClick={increasePopulation}>one up</button>
}
```