Skip to main content

Accessing state

1. Create the store

javascript
// store.ts import { create } from 'zustand' interface CounterState { count: number increase: () => void decrease: () => void } export const useCounterStore = create<CounterState>((set) => ({ count: 0, increase: () => set((state) => ({ count: state.count + 1 })), decrease: () => set((state) => ({ count: state.count - 1 })), }))

2. Use the store in a component

The store itself is a React hook that returns access to the state and actions.

Simple usage example:

javascript
// Counter.tsx import { useCounterStore } from './store' export function Counter() { const { count, increase, decrease } = useCounterStore() // <- calling the Zustand hook return ( <div> <p>Count: {count}</p> <button onClick={increase}>+</button> <button onClick={decrease}>-</button> </div> ) }

The React component automatically subscribes only to count, increase, and decrease. When those values change, the component re-renders.


3. Pull out only the part of the state you need (selectors)

So the component does not update when the whole state changes, you can select only the fields you need:

javascript
const count = useCounterStore((state) => state.count) const increase = useCounterStore((state) => state.increase)

or compactly:

javascript
const { count, increase } = useCounterStore((state) => ({ count: state.count, increase: state.increase, }))

This way the component will update only when specific fields change, not the whole store.


4. Accessing state outside React components

Zustand also lets you work with the store outside React (for example, in utilities or an API):

javascript
// Get the state console.log(useCounterStore.getState().count) // Update the state useCounterStore.setState({ count: 100 })

Summary

ScenarioHow to get the state
Inside a React componentconst value = useStore((s) => s.value)
Several fieldsconst { a, b } = useStore((s) => ({ a: s.a, b: s.b }))
Outside ReactuseStore.getState() / useStore.setState()
Manual subscriptionuseStore.subscribe(callback)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.