create-store.md
This file
Path
docs/reference/apis/create-store.md
518 lines · 14.8 KiB · Markdown
Last changed by
docs(create): document that state cannot be read during initialization (#3569)Daishi Katobefore adoptionb57db4f
History of this fileTake it
Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 1–39why, one step back1---2title: createStore3description: How to create vanilla stores4nav: 225---67`createStore` lets you create a vanilla store that exposes API utilities.89```js10const someStore = createStore(stateCreatorFn)11```1213- [Types](#types)14 - [Signature](#signature)15- [Reference](#reference)16- [Usage](#usage)17 - [Updating state based on previous state](#updating-state-based-on-previous-state)18 - [Updating Primitives in State](#updating-primitives-in-state)19 - [Updating Objects in State](#updating-objects-in-state)20 - [Updating Arrays in State](#updating-arrays-in-state)21 - [Subscribing to state updates](#subscribing-to-state-updates)22- [Troubleshooting](#troubleshooting)23 - [I’ve updated the state, but the screen doesn’t update](#i’ve-updated-the-state,-but-the-screen-doesn’t-update)2425## Types2627### Signature2829```ts30createStore<T>()(stateCreatorFn: StateCreator<T, [], []>): StoreApi<T>31```3233## Reference3435### `createStore(stateCreatorFn)`3637#### Parameters3839- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.docs(create): document that state cannot be read during initialization (#3569)Daishi Katobefore adoptionb57db4f
lines 40–41why, one step back40 Usually, you will return an object with the methods you want to expose. Note that `set`, `get` and41 `store` cannot be used while this function is running, only after the store has been created.Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9
lines 42–518why, one step back4243#### Returns4445`createStore` returns a vanilla store that exposes API utilities, `setState`, `getState`,46`getInitialState` and `subscribe`.4748## Usage4950### Updating state based on previous state5152This example shows how you can support **updater functions** within **actions**.5354```tsx55import { createStore } from 'zustand/vanilla'5657type AgeStoreState = { age: number }5859type AgeStoreActions = {60 setAge: (61 nextAge:62 | AgeStoreState['age']63 | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),64 ) => void65}6667type AgeStore = AgeStoreState & AgeStoreActions6869const ageStore = createStore<AgeStore>()((set) => ({70 age: 42,71 setAge: (nextAge) =>72 set((state) => ({73 age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,74 })),75}))7677function increment() {78 ageStore.getState().setAge((currentAge) => currentAge + 1)79}8081const $yourAgeHeading = document.getElementById(82 'your-age',83) as HTMLHeadingElement84const $incrementBy3Button = document.getElementById(85 'increment-by-3',86) as HTMLButtonElement87const $incrementBy1Button = document.getElementById(88 'increment-by-1',89) as HTMLButtonElement9091$incrementBy3Button.addEventListener('click', () => {92 increment()93 increment()94 increment()95})9697$incrementBy1Button.addEventListener('click', () => {98 increment()99})100101const render: Parameters<typeof ageStore.subscribe>[0] = (state) => {102 $yourAgeHeading.innerHTML = `Your age: ${state.age}`103}104105render(ageStore.getInitialState(), ageStore.getInitialState())106107ageStore.subscribe(render)108```109110Here's the `html` code111112```html113<h1 id="your-age"></h1>114<button id="increment-by-3" type="button">+3</button>115<button id="increment-by-1" type="button">+1</button>116```117118### Updating Primitives in State119120State can hold any kind of JavaScript value. When you want to update built-in primitive values like121numbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied122correctly, and avoid unexpected behaviors.123124> [!NOTE]125> By default, `set` function performs a shallow merge. If you need to completely replace126> the state with a new one, use the `replace` parameter set to `true`127128```ts129import { createStore } from 'zustand/vanilla'130131type XStore = number132133const xStore = createStore<XStore>()(() => 0)134135const $dotContainer = document.getElementById('dot-container') as HTMLDivElement136const $dot = document.getElementById('dot') as HTMLDivElement137138$dotContainer.addEventListener('pointermove', (event) => {139 xStore.setState(event.clientX, true)140})141142const render: Parameters<typeof xStore.subscribe>[0] = (x) => {143 $dot.style.transform = `translate(${x}px, 0)`144}145146render(xStore.getInitialState(), xStore.getInitialState())147148xStore.subscribe(render)149```150151Here's the `html` code152153```html154<div155 id="dot-container"156 style="position: relative; width: 100vw; height: 100vh;"157>158 <div159 id="dot"160 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"161 ></div>162</div>163```164165### Updating Objects in State166167Objects are **mutable** in JavaScript, but you should treat them as **immutable** when you store168them in state. Instead, when you want to update an object, you need to create a new one (or make a169copy of an existing one), and then set the state to use the new object.170171By default, `set` function performs a shallow merge. For most updates where you only need to modify172specific properties, the default shallow merge is preferred as it's more efficient. To completely173replace the state with a new one, use the `replace` parameter set to `true` with caution, as it174discards any existing nested data within the state.175176```ts177import { createStore } from 'zustand/vanilla'178179type PositionStoreState = { position: { x: number; y: number } }180181type PositionStoreActions = {182 setPosition: (nextPosition: PositionStoreState['position']) => void183}184185type PositionStore = PositionStoreState & PositionStoreActions186187const positionStore = createStore<PositionStore>()((set) => ({188 position: { x: 0, y: 0 },189 setPosition: (position) => set({ position }),190}))191192const $dotContainer = document.getElementById('dot-container') as HTMLDivElement193const $dot = document.getElementById('dot') as HTMLDivElement194195$dotContainer.addEventListener('pointermove', (event) => {196 positionStore.getState().setPosition({197 x: event.clientX,198 y: event.clientY,199 })200})201202const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {203 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`204}205206render(positionStore.getInitialState(), positionStore.getInitialState())207208positionStore.subscribe(render)209```210211Here's the `html` code212213```html214<div215 id="dot-container"216 style="position: relative; width: 100vw; height: 100vh;"217>218 <div219 id="dot"220 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"221 ></div>222</div>223```224225### Updating Arrays in State226227Arrays are mutable in JavaScript, but you should treat them as immutable when you store them in228state. Just like with objects, when you want to update an array stored in state, you need to create229a new one (or make a copy of an existing one), and then set state to use the new array.230231By default, `set` function performs a shallow merge. To update array values we should assign new232values to ensure updates are applied correctly, and avoid unexpected behaviors. To completely233replace the state with a new one, use the `replace` parameter set to `true`.234235> [!IMPORTANT]236> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,237> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid238> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,239> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.240241```ts242import { createStore } from 'zustand/vanilla'243244type PositionStore = [number, number]245246const positionStore = createStore<PositionStore>()(() => [0, 0])247248const $dotContainer = document.getElementById('dot-container') as HTMLDivElement249const $dot = document.getElementById('dot') as HTMLDivElement250251$dotContainer.addEventListener('pointermove', (event) => {252 positionStore.setState([event.clientX, event.clientY], true)253})254255const render: Parameters<typeof positionStore.subscribe>[0] = ([x, y]) => {256 $dot.style.transform = `translate(${x}px, ${y}px)`257}258259render(positionStore.getInitialState(), positionStore.getInitialState())260261positionStore.subscribe(render)262```263264Here's the `html` code265266```html267<div268 id="dot-container"269 style="position: relative; width: 100vw; height: 100vh;"270>271 <div272 id="dot"273 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"274 ></div>275</div>276```277278### Subscribing to state updates279280By subscribing to state updates, you register a callback that fires whenever the store's state281updates. We can use `subscribe` for external state management.282283```ts284import { createStore } from 'zustand/vanilla'285286type PositionStoreState = { position: { x: number; y: number } }287288type PositionStoreActions = {289 setPosition: (nextPosition: PositionStoreState['position']) => void290}291292type PositionStore = PositionStoreState & PositionStoreActions293294const positionStore = createStore<PositionStore>()((set) => ({295 position: { x: 0, y: 0 },296 setPosition: (position) => set({ position }),297}))298299const $dot = document.getElementById('dot') as HTMLDivElement300301$dot.addEventListener('mouseenter', (event) => {302 const parent = event.currentTarget.parentElement303 const parentWidth = parent.clientWidth304 const parentHeight = parent.clientHeight305306 positionStore.getState().setPosition({307 x: Math.ceil(Math.random() * parentWidth),308 y: Math.ceil(Math.random() * parentHeight),309 })310})311312const render: Parameters<typeof positionStore.subscribe>[0] = (state) => {313 $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`314}315316render(positionStore.getInitialState(), positionStore.getInitialState())317318positionStore.subscribe(render)319320const logger: Parameters<typeof positionStore.subscribe>[0] = (state) => {321 console.log('new position', { position: state.position })322}323324positionStore.subscribe(logger)325```326327Here's the `html` code328329```html330<div331 id="dot-container"332 style="position: relative; width: 100vw; height: 100vh;"333>334 <div335 id="dot"336 style="position: absolute; background-color: red; border-radius: 50%; left: -10px; top: -10px; width: 20px; height: 20px;"337 ></div>338</div>339```340341## Troubleshooting342343### I’ve updated the state, but the screen doesn’t update344345In the previous example, the `position` object is always created fresh from the current cursor346position. But often, you will want to include existing data as a part of the new object you’re347creating. For example, you may want to update only one field in a form, but keep the previous348values for all other fields.349350These input fields don’t work because the `oninput` handlers mutate the state:351352```ts353import { createStore } from 'zustand/vanilla'354355type PersonStoreState = {356 person: { firstName: string; lastName: string; email: string }357}358359type PersonStoreActions = {360 setPerson: (nextPerson: PersonStoreState['person']) => void361}362363type PersonStore = PersonStoreState & PersonStoreActions364365const personStore = createStore<PersonStore>()((set) => ({366 person: {367 firstName: 'Barbara',368 lastName: 'Hepworth',369 email: 'bhepworth@sculpture.com',370 },371 setPerson: (person) => set({ person }),372}))373374const $firstNameInput = document.getElementById(375 'first-name',376) as HTMLInputElement377const $lastNameInput = document.getElementById('last-name') as HTMLInputElement378const $emailInput = document.getElementById('email') as HTMLInputElement379const $result = document.getElementById('result') as HTMLDivElement380381function handleFirstNameChange(event: Event) {382 personStore.getState().person.firstName = (event.target as any).value383}384385function handleLastNameChange(event: Event) {386 personStore.getState().person.lastName = (event.target as any).value387}388389function handleEmailChange(event: Event) {390 personStore.getState().person.email = (event.target as any).value391}392393$firstNameInput.addEventListener('input', handleFirstNameChange)394$lastNameInput.addEventListener('input', handleLastNameChange)395$emailInput.addEventListener('input', handleEmailChange)396397const render: Parameters<typeof personStore.subscribe>[0] = (state) => {398 $firstNameInput.value = state.person.firstName399 $lastNameInput.value = state.person.lastName400 $emailInput.value = state.person.email401402 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`403}404405render(personStore.getInitialState(), personStore.getInitialState())406407personStore.subscribe(render)408```409410Here's the `html` code411412```html413<label style="display: block">414 First name:415 <input id="first-name" />416</label>417<label style="display: block">418 Last name:419 <input id="last-name" />420</label>421<label style="display: block">422 Email:423 <input id="email" />424</label>425<p id="result"></p>426```427428For example, this line mutates the state from a past render:429430```ts431personStore.getState().firstName = (e.target as any).value432```433434The reliable way to get the behavior you’re looking for is to create a new object and pass it to435`setPerson`. But here you want to also copy the existing data into it because only one of the436fields has changed:437438```ts439personStore.getState().setPerson({440 firstName: e.target.value, // New first name from the input441})442```443444> [!NOTE]445> We don’t need to copy every property separately due to `set` function performing shallow merge by446> default.447448Now the form works!449450Notice how you didn’t declare a separate state variable for each input field. For large forms,451keeping all data grouped in an object is very convenient—as long as you update it correctly!452453```ts {32-34,38-40,44-46}454import { createStore } from 'zustand/vanilla'455456type PersonStoreState = {457 person: { firstName: string; lastName: string; email: string }458}459460type PersonStoreActions = {461 setPerson: (nextPerson: PersonStoreState['person']) => void462}463464type PersonStore = PersonStoreState & PersonStoreActions465466const personStore = createStore<PersonStore>()((set) => ({467 person: {468 firstName: 'Barbara',469 lastName: 'Hepworth',470 email: 'bhepworth@sculpture.com',471 },472 setPerson: (person) => set({ person }),473}))474475const $firstNameInput = document.getElementById(476 'first-name',477) as HTMLInputElement478const $lastNameInput = document.getElementById('last-name') as HTMLInputElement479const $emailInput = document.getElementById('email') as HTMLInputElement480const $result = document.getElementById('result') as HTMLDivElement481482function handleFirstNameChange(event: Event) {483 personStore.getState().setPerson({484 ...personStore.getState().person,485 firstName: (event.target as any).value,486 })487}488489function handleLastNameChange(event: Event) {490 personStore.getState().setPerson({491 ...personStore.getState().person,492 lastName: (event.target as any).value,493 })494}495496function handleEmailChange(event: Event) {497 personStore.getState().setPerson({498 ...personStore.getState().person,499 email: (event.target as any).value,500 })501}502503$firstNameInput.addEventListener('input', handleFirstNameChange)504$lastNameInput.addEventListener('input', handleLastNameChange)505$emailInput.addEventListener('input', handleEmailChange)506507const render: Parameters<typeof personStore.subscribe>[0] = (state) => {508 $firstNameInput.value = state.person.firstName509 $lastNameInput.value = state.person.lastName510 $emailInput.value = state.person.email511512 $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`513}514515render(personStore.getInitialState(), personStore.getInitialState())516517personStore.subscribe(render)518```