Zustand 렌더링 최적화

유의진·2024년 12월 15일
2

찍찍이

목록 보기
1/6
post-thumbnail

Zustand 의 기본 사용법

zustand는 Store를 만들어 전역변수를 간편하게 사용할 수 있는 라이브러리이다.

zustand를 사용해서 Store에서 상태를 가져오는 방식이 2가지 있다.

const { value } = useStore();
const value = useStore((state) => state.value);

Selector function이란?

기본적으로 React 컴포넌트가 상태를 가져오면 상태 변화가 있을 때마다 해당 컴포넌트가 다시 렌더링 된다.
하지만 Zustand는 상태의 특정 부분만 선택적으로 가져올 수 있기 때문에 상태 변화가 특정 부분에서만 영향을 미치도록 제한할 수 있다.

기본적인 zustand 사용


export const Sidebar = () => {
  // ...
  const { toggleIsNew } = useNewGoalsStore(); // 전체 상태를 가져온다.
  
  // ...

    <MenuItem
      icon={<FaFlag className="size-28 p-4" />}
      label="목표"
      addButton={
        <SidebarButton type="default" onClick={toggleIsNew}>
          새 목표
        </SidebarButton>
      }
    />

  //...

불필요한 리렌더링 방지 zustand 사용

export const Sidebar = () => {
  // ...
  const handleToggle = useNewGoalsStore((state) => state.toggleIsNew); // 특정 상태만 가져온다.

  // ...
  
    <MenuItem
      icon={<FaFlag className="size-28 p-4" />}
      label="목표"
      addButton={
        <SidebarButton type="default" onClick={handleToggle}>
          새 목표
        </SidebarButton>
      }
    />

  // ...

참고

Zustand 공식문서
https://zustand-demo.pmnd.rs/

selector 관련 zustand 공식 github
https://github.com/pmndrs/zustand#Recipes

profile
안녕하세요. 프론트엔드 개발 공부를 하고 있습니다.

0개의 댓글

관련 채용 정보