Sub topic 2
Controlling Re-renders and Using `useShallow`
This chapter assumes you know React function components and hooks, JavaScript or TypeScript modules, and immutable updates.
Select Only What a Component Needs
A Zustand selector is a function that chooses part of the store. A component re-renders when its selected value changes.
import { useCounterStore } from './counterStore'
function Count() {
const count = useCounterStore((state) => state.count)
return <p>Count: {count}</p>
}
function Controls() {
const increment = useCounterStore((state) => state.increment)
return <button onClick={increment}>Add one</button>
}Controls does not re-render when count changes because its selected function stays the same.
Avoid selecting the whole store:
const state = useCounterStore((state) => state)This component observes every change, including unrelated changes.
Selecting Several Values
A selector that returns a new object creates a new reference on each call. Use useShallow when you need multiple top-level fields.
import { useShallow } from 'zustand/react/shallow'
import { useUserStore } from './userStore'
function Profile() {
const { name, email } = useUserStore(
useShallow((state) => ({ name: state.name, email: state.email })),
)
return <p>{name} ({email})</p>
}useShallow compares the selected object's top-level values. Profile re-renders when name or email changes, but not when an unrelated field changes.
Derive Values Instead of Storing Them
Derived state is a value calculated from existing state. Do not store values such as completedCount when they can become stale.
const completedCount = useTodoStore(
(state) => state.todos.filter((todo) => todo.done).length,
)For expensive calculations, use a carefully selected input or memoization. Keep the source of truth in the store.
Async Actions
Actions can be asynchronous. Set loading and error state around the request.
fetchUsers: async () => {
set({ loading: true, error: null })
try {
const response = await fetch('/api/users')
if (!response.ok) throw new Error(`Request failed: ${response.status}`)
set({ users: await response.json(), loading: false })
} catch (error) {
set({
error: error instanceof Error ? error.message : 'Unknown error',
loading: false,
})
}
}TypeScript and Non-React Access
Define the state and actions together with create<T>()(...). The returned hook also exposes getState, setState, and subscribe, which are useful for services and tests.
interface CounterState {
count: number
increment: () => void
}
export const useCounterStore = create<CounterState>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
const current = useCounterStore.getState().count
useCounterStore.setState({ count: 10 })
const unsubscribe = useCounterStore.subscribe((state) => {
console.log(state.count)
})
unsubscribe()Exercise
Why might a selector returning { count: state.count } cause extra renders, and which Zustand helper addresses this?
Show answer
It creates a new object reference each time. useShallow compares its top-level fields.