Zustand에서 상태를 가져오는 방식에 따라 리렌더링 빈도와 성능이 달라진다.
핵심은 selector가 무엇을 반환하느냐다.
const hasStarted = useTabStore(state => state.hasStarted);
const setHasStarted = useTabStore(state => state.setHasStarted);
const { hasStarted, setHasStarted } =
useTabStore(state => ({
hasStarted: state.hasStarted,
setHasStarted: state.setHasStarted,
}));
import { shallow } from 'zustand/shallow';
const { hasStarted, setHasStarted } =
useTabStore(
state => ({
hasStarted: state.hasStarted,
setHasStarted: state.setHasStarted,
}),
shallow
);
| 방식 | 리렌더링 | 추천 |
|---|---|---|
| 개별 선택자 | 정확 | ✅ |
| 구조 분해 + shallow | 정확 | ✅ |
| 구조 분해 (shallow 없음) | 과도 | ❌ |
Zustand에서 객체를 반환하는 selector를 쓰면
반드시 shallow를 함께 사용하자
이 방법으로 불필요한 리렌더링을 피할 수 있다!