Zustand + immer.js

박요셉·2024년 7월 19일

Simple note

목록 보기
10/18

immer.js가 불변성 유지에 매우 강력하다는 말이 있었음.
RTK를 쓸 땐 기본적으로 적용이 되어 있었는데 zustand에는 그게 안되어있으니 은근 불변성 유지를 신경써야되서 불편함을 느꼇던 것 같음.

이번 프로젝트에서 zustand를 써서 클라이언트 쪽의 상태관리를 한다면 immer.js또한 같이 쓰는게 어떨까 싶어서 간단한 예제코드 하나만 첨부해놓게씀.

import create from 'zustand';
import produce from 'immer';

interface State {
  bears: number;
  increase: () => void;
}

const useStore = create<State>((set) => ({
  bears: 0,
  increase: () => set((state) =>
    produce(state, (draft) => {
      draft.bears += 1;
    })
  ),
}));

function BearCounter() {
  const bears = useStore((state) => state.bears);
  const increase = useStore((state) => state.increase);
  return (
    <div>
      <h1>{bears} bears</h1>
      <button onClick={increase}>Increase</button>
    </div>
  );
}

export default BearCounter;
profile
개발자 지망생

1개의 댓글

comment-user-thumbnail
2024년 7월 27일

예제까지.. 줍줍해갈게요 ! ㅋㅋㅋ

답글 달기