introduction.md
This file
Path
docs/learn/getting-started/introduction.md
72 lines · 2.0 KiB · Markdown
Last changed by
Fix README internal links for GitHub rendering (#3403)Copilotbefore adoptionda381c3
History of this fileTake it
Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 1–7why, one step back1---2title: Introduction3description: How to use Zustand4nav: 15---67<div class="flex justify-center mb-4">Fix README internal links for GitHub rendering (#3403)Copilotbefore adoptionda381c3
line 8why, one step back8<img src="../../bear.jpg" alt="Logo Zustand" />Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 9–72why, one step back9</div>1011A small, fast, and scalable bearbones state management solution.12Zustand has a comfy API based on hooks.13It isn't boilerplatey or opinionated,14but has enough convention to be explicit and flux-like.1516Don't disregard it because it's cute, it has claws!17Lots of time was spent to deal with common pitfalls,18like the dreaded [zombie child problem],19[React concurrency], and [context loss]20between mixed renderers.21It may be the one state manager in the React space that gets all of these right.2223You can try a live demo [here](https://codesandbox.io/s/dazzling-moon-itop4).2425[zombie child problem]: https://react-redux.js.org/api/hooks#stale-props-and-zombie-children26[react concurrency]: https://github.com/bvaughn/rfcs/blob/useMutableSource/text/0000-use-mutable-source.md27[context loss]: https://github.com/facebook/react/issues/133322829## Installation3031Zustand is available as a package on NPM for use:3233```bash34# NPM35npm install zustand36# Or, use any package manager of your choice.37```3839## First create a store4041Your store is a hook!42You can put anything in it: primitives, objects, functions.43The `set` function _merges_ state.4445```js46import { create } from 'zustand'4748const useBear = create((set) => ({49 bears: 0,50 increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),51 removeAllBears: () => set({ bears: 0 }),52 updateBears: (newBears) => set({ bears: newBears }),53}))54```5556## Then bind your components, and that's it!5758You can use the hook anywhere, without the need of providers.59Select your state and the consuming component60will re-render when that state changes.6162```jsx63function BearCounter() {64 const bears = useBear((state) => state.bears)65 return <h1>{bears} bears around here...</h1>66}6768function Controls() {69 const increasePopulation = useBear((state) => state.increasePopulation)70 return <button onClick={increasePopulation}>one up</button>71}72```