Skip to content
Myr

create.md

This file

Path

docs/reference/apis/create.md

572 lines · 15.2 KiB · Markdown

Last changed by

docs(create): document that state cannot be read during initialization (#3569)Daishi Katobefore adoptionb57db4f

History of this file

Take it

Show it rendered

1---2title: create3description: How to create stores4tag: react5nav: 216---78`create` lets you create a React Hook with API utilities attached.910```js11const useSomeStore = create(stateCreatorFn)12```1314- [Types](#types)15  - [Signature](#signature)16- [Reference](#reference)17- [Usage](#usage)18  - [Updating state based on previous state](#updating-state-based-on-previous-state)19  - [Updating Primitives in State](#updating-primitives-in-state)20  - [Updating Objects in State](#updating-objects-in-state)21  - [Updating Arrays in State](#updating-arrays-in-state)22  - [Updating state with no store actions](#updating-state-with-no-store-actions)23  - [Subscribing to state updates](#subscribing-to-state-updates)24- [Troubleshooting](#troubleshooting)25  - [I’ve updated the state, but the screen doesn’t update](#i’ve-updated-the-state,-but-the-screen-doesn’t-update)2627## Types2829### Signature3031```ts32create<T>()(stateCreatorFn: StateCreator<T, [], []>): UseBoundStore<StoreApi<T>>33```3435## Reference3637### `create(stateCreatorFn)`3839#### Parameters4041- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.42  Usually, you will return an object with the methods you want to expose. Note that `set`, `get` and43  `store` cannot be used while this function is running, only after the store has been created.4445#### Returns4647`create` returns a React Hook with API utilities, `setState`, `getState`, `getInitialState` and48`subscribe`, attached. It lets you return data that is based on current state, using a selector49function. It should take a selector function as its only argument.5051## Usage5253### Updating state based on previous state5455To update a state based on previous state we should use **updater functions**. Read more56about that [here](https://react.dev/learn/queueing-a-series-of-state-updates).5758This example shows how you can support **updater functions** within **actions**.5960```tsx61import { create } from 'zustand'6263type AgeStoreState = { age: number }6465type AgeStoreActions = {66  setAge: (67    nextAge:68      | AgeStoreState['age']69      | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),70  ) => void71}7273type AgeStore = AgeStoreState & AgeStoreActions7475const useAgeStore = create<AgeStore>()((set) => ({76  age: 42,77  setAge: (nextAge) => {78    set((state) => ({79      age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,80    }))81  },82}))8384export default function App() {85  const age = useAgeStore((state) => state.age)86  const setAge = useAgeStore((state) => state.setAge)8788  function increment() {89    setAge((currentAge) => currentAge + 1)90  }9192  return (93    <>94      <h1>Your age: {age}</h1>95      <button96        onClick={() => {97          increment()98          increment()99          increment()100        }}101      >102        +3103      </button>104      <button105        onClick={() => {106          increment()107        }}108      >109        +1110      </button>111    </>112  )113}114```115116### Updating Primitives in State117118State can hold any kind of JavaScript value. When you want to update built-in primitive values like119numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied120correctly, and avoid unexpected behaviors.121122> [!NOTE]123> By default, `set` function performs a shallow merge. If you need to completely replace the state124> with a new one, use the `replace` parameter set to `true`125126```tsx127import { create } from 'zustand'128129type XStore = number130131const useXStore = create<XStore>()(() => 0)132133export default function MovingDot() {134  const x = useXStore()135  const setX = (nextX: number) => {136    useXStore.setState(nextX, true)137  }138  const position = { y: 0, x }139140  return (141    <div142      onPointerMove={(e) => {143        setX(e.clientX)144      }}145      style={{146        position: 'relative',147        width: '100vw',148        height: '100vh',149      }}150    >151      <div152        style={{153          position: 'absolute',154          backgroundColor: 'red',155          borderRadius: '50%',156          transform: `translate(${position.x}px, ${position.y}px)`,157          left: -10,158          top: -10,159          width: 20,160          height: 20,161        }}162      />163    </div>164  )165}166```167168### Updating Objects in State169170Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store171them in state. Instead, when you want to update an object, you need to create a new one (or make a172copy of an existing one), and then set the state to use the new object.173174By default, `set` function performs a shallow merge. For most updates where you only need to modify175specific properties, the default shallow merge is preferred as it's more efficient. To completely176replace the state with a new one, use the `replace` parameter set to `true` with caution, as it177discards any existing nested data within the state.178179```tsx180import { create } from 'zustand'181182type PositionStoreState = { position: { x: number; y: number } }183184type PositionStoreActions = {185  setPosition: (nextPosition: PositionStoreState['position']) => void186}187188type PositionStore = PositionStoreState & PositionStoreActions189190const usePositionStore = create<PositionStore>()((set) => ({191  position: { x: 0, y: 0 },192  setPosition: (nextPosition) => set({ position: nextPosition }),193}))194195export default function MovingDot() {196  const position = usePositionStore((state) => state.position)197  const setPosition = usePositionStore((state) => state.setPosition)198199  return (200    <div201      onPointerMove={(e) => {202        setPosition({203          x: e.clientX,204          y: e.clientY,205        })206      }}207      style={{208        position: 'relative',209        width: '100vw',210        height: '100vh',211      }}212    >213      <div214        style={{215          position: 'absolute',216          backgroundColor: 'red',217          borderRadius: '50%',218          transform: `translate(${position.x}px, ${position.y}px)`,219          left: -10,220          top: -10,221          width: 20,222          height: 20,223        }}224      />225    </div>226  )227}228```229230### Updating Arrays in State231232Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in233state. Just like with objects, when you want to update an array stored in state, you need to create234a new one (or make a copy of an existing one), and then set state to use the new array.235236By default, `set` function performs a shallow merge. To update array values we should assign new237values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely238replace the state with a new one, use the `replace` parameter set to `true`.239240> [!IMPORTANT]241> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,242> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid243> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,244> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.245246```tsx247import { create } from 'zustand'248249type PositionStore = [number, number]250251const usePositionStore = create<PositionStore>()(() => [0, 0])252253export default function MovingDot() {254  const [x, y] = usePositionStore()255  const setPosition: typeof usePositionStore.setState = (nextPosition) => {256    usePositionStore.setState(nextPosition, true)257  }258  const position = { x, y }259260  return (261    <div262      onPointerMove={(e) => {263        setPosition([e.clientX, e.clientY])264      }}265      style={{266        position: 'relative',267        width: '100vw',268        height: '100vh',269      }}270    >271      <div272        style={{273          position: 'absolute',274          backgroundColor: 'red',275          borderRadius: '50%',276          transform: `translate(${position.x}px, ${position.y}px)`,277          left: -10,278          top: -10,279          width: 20,280          height: 20,281        }}282      />283    </div>284  )285}286```287288### Updating state with no store actions289290Defining actions at module level, external to the store have a few advantages like: it doesn't291require a hook to call an action, and it facilitates code splitting.292293> [!NOTE]294> The recommended way is to colocate actions and states within the store (let your actions be295> located together with your state).296297```tsx298import { create } from 'zustand'299300const usePositionStore = create<{301  x: number302  y: number303}>()(() => ({ x: 0, y: 0 }))304305const setPosition: typeof usePositionStore.setState = (nextPosition) => {306  usePositionStore.setState(nextPosition)307}308309export default function MovingDot() {310  const position = usePositionStore()311312  return (313    <div314      style={{315        position: 'relative',316        width: '100vw',317        height: '100vh',318      }}319    >320      <div321        style={{322          position: 'absolute',323          backgroundColor: 'red',324          borderRadius: '50%',325          transform: `translate(${position.x}px, ${position.y}px)`,326          left: -10,327          top: -10,328          width: 20,329          height: 20,330        }}331        onMouseEnter={(event) => {332          const parent = event.currentTarget.parentElement333          const parentWidth = parent.clientWidth334          const parentHeight = parent.clientHeight335336          setPosition({337            x: Math.ceil(Math.random() * parentWidth),338            y: Math.ceil(Math.random() * parentHeight),339          })340        }}341      />342    </div>343  )344}345```346347### Subscribing to state updates348349By subscribing to state updates, you register a callback that fires whenever the store's state350updates. We can use `subscribe` for external state management.351352```tsx353import { useEffect } from 'react'354import { create } from 'zustand'355356type PositionStoreState = { position: { x: number; y: number } }357358type PositionStoreActions = {359  setPosition: (nextPosition: PositionStoreState['position']) => void360}361362type PositionStore = PositionStoreState & PositionStoreActions363364const usePositionStore = create<PositionStore>()((set) => ({365  position: { x: 0, y: 0 },366  setPosition: (nextPosition) => set({ position: nextPosition }),367}))368369export default function MovingDot() {370  const position = usePositionStore((state) => state.position)371  const setPosition = usePositionStore((state) => state.setPosition)372373  useEffect(() => {374    const unsubscribePositionStore = usePositionStore.subscribe(375      ({ position }) => {376        console.log('new position', { position })377      },378    )379380    return () => {381      unsubscribePositionStore()382    }383  }, [])384385  return (386    <div387      style={{388        position: 'relative',389        width: '100vw',390        height: '100vh',391      }}392    >393      <div394        style={{395          position: 'absolute',396          backgroundColor: 'red',397          borderRadius: '50%',398          transform: `translate(${position.x}px, ${position.y}px)`,399          left: -10,400          top: -10,401          width: 20,402          height: 20,403        }}404        onMouseEnter={(event) => {405          const parent = event.currentTarget.parentElement406          const parentWidth = parent.clientWidth407          const parentHeight = parent.clientHeight408409          setPosition({410            x: Math.ceil(Math.random() * parentWidth),411            y: Math.ceil(Math.random() * parentHeight),412          })413        }}414      />415    </div>416  )417}418```419420## Troubleshooting421422### I’ve updated the state, but the screen doesn’t update423424In the previous example, the `position` object is always created fresh from the current cursor425position. But often, you will want to include existing data as a part of the new object you’re426creating. For example, you may want to update only one field in a form, but keep the previous427values for all other fields.428429These input fields don’t work because the `onChange` handlers mutate the state:430431```tsx432import { create } from 'zustand'433434type PersonStoreState = {435  firstName: string436  lastName: string437  email: string438}439440type PersonStoreActions = {441  setPerson: (nextPerson: Partial<PersonStoreState>) => void442}443444type PersonStore = PersonStoreState & PersonStoreActions445446const usePersonStore = create<PersonStore>()((set) => ({447  firstName: 'Barbara',448  lastName: 'Hepworth',449  email: 'bhepworth@sculpture.com',450  setPerson: (nextPerson) => set(nextPerson),451}))452453export default function Form() {454  const person = usePersonStore((state) => state)455  const setPerson = usePersonStore((state) => state.setPerson)456457  function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {458    person.firstName = e.target.value459  }460461  function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {462    person.lastName = e.target.value463  }464465  function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {466    person.email = e.target.value467  }468469  return (470    <>471      <label style={{ display: 'block' }}>472        First name:473        <input value={person.firstName} onChange={handleFirstNameChange} />474      </label>475      <label style={{ display: 'block' }}>476        Last name:477        <input value={person.lastName} onChange={handleLastNameChange} />478      </label>479      <label style={{ display: 'block' }}>480        Email:481        <input value={person.email} onChange={handleEmailChange} />482      </label>483      <p>484        {person.firstName} {person.lastName} ({person.email})485      </p>486    </>487  )488}489```490491For example, this line mutates the state from a past render:492493```tsx494person.firstName = e.target.value495```496497The reliable way to get the behavior you’re looking for is to create a new object and pass it to498`setPerson`. But here you want to also copy the existing data into it because only one of the499fields has changed:500501```ts502setPerson({ ...person, firstName: e.target.value }) // New first name from the input503```504505> [!NOTE]506> We don’t need to copy every property separately due to `set` function performing shallow merge by507> default.508509Now the form works!510511Notice how you didn’t declare a separate state variable for each input field. For large forms,512keeping all data grouped in an object is very convenient—as long as you update it correctly!513514```tsx {27,31,35}515import { create } from 'zustand'516517type PersonStoreState = {518  person: { firstName: string; lastName: string; email: string }519}520521type PersonStoreActions = {522  setPerson: (nextPerson: PersonStoreState['person']) => void523}524525type PersonStore = PersonStoreState & PersonStoreActions526527const usePersonStore = create<PersonStore>()((set) => ({528  person: {529    firstName: 'Barbara',530    lastName: 'Hepworth',531    email: 'bhepworth@sculpture.com',532  },533  setPerson: (nextPerson) => set(nextPerson),534}))535536export default function Form() {537  const person = usePersonStore((state) => state.person)538  const setPerson = usePersonStore((state) => state.setPerson)539540  function handleFirstNameChange(e: ChangeEvent<HTMLInputElement>) {541    setPerson({ ...person, firstName: e.target.value })542  }543544  function handleLastNameChange(e: ChangeEvent<HTMLInputElement>) {545    setPerson({ ...person, lastName: e.target.value })546  }547548  function handleEmailChange(e: ChangeEvent<HTMLInputElement>) {549    setPerson({ ...person, email: e.target.value })550  }551552  return (553    <>554      <label style={{ display: 'block' }}>555        First name:556        <input value={person.firstName} onChange={handleFirstNameChange} />557      </label>558      <label style={{ display: 'block' }}>559        Last name:560        <input value={person.lastName} onChange={handleLastNameChange} />561      </label>562      <label style={{ display: 'block' }}>563        Email:564        <input value={person.email} onChange={handleEmailChange} />565      </label>566      <p>567        {person.firstName} {person.lastName} ({person.email})568      </p>569    </>570  )571}572```