본문 바로가기
Front-end

🐻zustand 이해하기

by FuterNomad 2023. 1. 16.

What is zustand?

zustand란 단순화한 flux원칙을 사용하는 작고, 빠르고 확장 가능한 아주 기본적인 상태 관리 solution이다.

 

Why zustand over other state management?

Redux를 넘어서는 이유.

  • 단순하고, 편향적이지 않다. Simple and un-opinionated
    • 'un-opinioned'의 뜻은 개발자들은 지속가능한 clean code의 quallity를 보장하는 일종의 패턴을 따르고 있는지 확실하게 해야한다는 의미를 담고 있습니다.
  • hook을 통해 상태 소비에 주요 수단으로 사용한다.
  • context provider로 app을 감싸지 않는다.
  • component에게 렌더링을 발생시키지 않고 상태를 전달할 수 있다.

context를 넘어서는 이유.

  • boilerplate가 적다.
  • 변경 시에만 component가 렌더링된다.
  • 중앙집중형, 행동 기반 상태 관리

🧸 More Detail about zustand

  • 발행/구독 모델 pub/sub
    • store에 상태 변경이 일어날 때 실행할 listner 함수에 모아두었다가 → "구독"
    • 상태가 변경 되었을 때, 등록된 listner들에게 상태가 변경되었음을 알려준다. → "발행"
  • 한 개의 중앙에 집중된 형식의 store 구조 활용
  • store를 생성하는 함수를 호출할 때 closure 활용
closure : 함수와 함수가 선언된 어휘적 환경의 조합
→ 내부 함수로부터 외부 함수의 스코프가 접근할 수 있는 권한을 주는 것을 의미합니다.

 


  zustand 사용법  

1. store 생성

import create from 'zustand';

// set 함수를 통해서만 상태를 변경할 수 있다
const useStore = create(set => ({
  bears: 0,
  increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 })
}));

store는 hook이다!

store를 생성할 때 create 함수를 이용하여 state와 그 state를 변경하는 action을 정의한다.

 

2. store 사용

// 상태를 꺼낸다
function BearCounter() {
  const bears = useStore(state => state.bears);
  return <h1>{bears} around here ...</h1>;
}

// 상태를 변경하는 액션을 꺼낸다
function Controls() {
  const increasePopulation = useStore(state => state.increasePopulation);
  return <button onClick={increasePopulation}>one up</button>;
}

useStore hook을 사용할 때 store에서 상태를 어떤 형태로 꺼낼지 결정하는 selector 함수를 전달하지 않는 경우 전체가 return된다.


References

https://medium.com/@victorvarghese/bear-necessities-for-state-management-with-react-query-zustand-bd7a69295acb
https://ui.toast.com/posts/ko_20210812
https://github.com/pmndrs/zustand
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures