기본적으로 엄격한 동등성 비교(oldState === newState
)로 변경을 감지합니다. 이 방법은 원자 상태 선택에 효율적입니다.
import { useStore } from './store';
function Component() {
**const nuts = useStore((state) => state.nuts);
const honey = useStore((state) => state.honey);**
return (...);
}
리-렌더링에 대한 제어를 위한 두번째 인수에 compare 함수를 사용해 비교할 수 있습니다.
const treats = useStore(
// 셀렉터 함수
(state) => state.treats,
// 비교 함수
**(oldTreats, newTreats) => compare(oldTreats, newTreats),**
);
예를 들어 Redux의 mapStateToProps
와 유사하게 내부에 여러 상태 셀렉터가 포함된 단일 객체를 구성하려는 경우, Zustand의 shallow
(얕은) 비교 함수를 사용해 Zustand에 알릴 수 있습니다.
**import { shallow } from 'zustand/shallow';**
// 객체로 여러 상태 슬라이스
// state.nuts, state.honey가 변경되면 컴포넌트 리-렌더링
const { nuts, honey } = useStore(
(state) => ({ nuts: state.nuts, honey: state.honey }),
**shallow,**
);
// 배열로 여러 상태 슬라이스
// state.nuts, state.honey가 변경되면 컴포넌트 리-렌더링
const [ nuts, honey ] = useStore(
(state) => [state.nuts, state.honey],
**shallow,**
);
// 맵으로 여러 상태 슬라이스
// state.treats의 순서 또는 갯수, 키 등이 변경되면 컴포넌트 리-렌더링
const treats = useStore(
(state) => Object.keys(state.treats),
**shallow,**
);
COPYRIGHT 2020 @ EUID