Using selectors
- React course
- Advanced
- Lesson 27/56
- 4 min
Learn to take only needed state with a selector and reduce renders.
Shallow comparison
When reading multiple values, calling useStore with a selector triggers render on every change. To avoid this, you use a shallow comparator.
You import it with import { shallow } from 'zustand/shallow' and call useStore((s) => ({ a: s.a, b: s.b }), shallow). This triggers render only when a or b changes.
Shallow compares each field of the object; even if the reference changes, equal values prevent render.
Selector best practice
A selector should return only the smallest needed piece. useStore((s) => s.user.name) reads only the name; even if user changes, no render if name is the same.
This fine-grained selector cuts React's rerender cost significantly; it matters especially in large lists.
Avoid creating new objects in selectors; a new reference on every call triggers render every time. That is why shallow is used.
Practice Read two values with shallow
Complete the skeleton. Write a Counter component. Call useCounter with selector (s) => ({ count: s.count, name: s.name }) and shallow. Import shallow from 'zustand/shallow'. Render <p>{name}: {count}</p>. Add export default.
Starter code
import { shallow } from 'zustand/shallow';
import { useCounter } from './useCounter';
// Write Counter hereSample solution
import { shallow } from 'zustand/shallow';
import { useCounter } from './useCounter';
function Counter() {
const { count, name } = useCounter(
(s) => ({ count: s.count, name: s.name }),
shallow
);
return <p>{name}: {count}</p>;
}
export default Counter;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When do you use shallow?
Many values = shallow.- When reading a single value
- Only when writing CSS
- When reading multiple values Correct answer
- Only during tests
Explanation: shallow is used for multiple values.
2 shallow import
import { ____ } from 'zustand/shallow';
import { shallow } from 'zustand/shallow';
Explanation: shallow is imported from zustand/shallow.
3 Using selectors: match the terms
| Term | Meaning |
|---|---|
shallow |
Comparator |
selector |
Relevant piece |
create |
Builds store |
set |
Updates state |