본문 바로가기
Library & Framework/Zustand

[Zustand] get()을 사용하여 최신값 가져오기

by 썸머워즈 2024. 4. 3.
반응형
"react": "^18.2.0",
"zustand": "^4.5.2"
"typescript": "^5.2.2"

get은 도대체 언제 쓰는 걸까?

얼핏 zustand를 살펴보면 set/get을 제공해주고 있는데 get이라는 녀석을 언제 쓰라고 제공해 주는 건지 의아하다.

Read from state in actions

혹시나 공식문서에 나와있나 살펴보면 Read from state in actions라는 세션으로 설명을 해주고 있다.

const useSoundStore = create((set, get) => ({
  sound: 'grunt',
  action: () => {
    const sound = get().sound
    ...

이러한 사용 방식은 store의 action 함수를 선언할 때 현재 store state값에 접근하여 활용하고자 할 때 사용할 수 있다.

최신값이 필요한 상황에서의 활용

이러한 활용방식이 별도로 공식문서에 정의되어 있는 건 아니지만,

store 내부에서 get을 통해 store state값에 직접 접근한다는 건 알 수 있다.

 

예를 들어 만약 구현을 하다가 의도치 않게 클로저가 발생하는 순간이 온다면?
아무 생각 없이 EventListener + useState 조합을 사용했을 때 이벤트 리스너의 콜백함수에서 그 순간의 state값을 들고 있기 때문에 값이 변경되지 않을 것이다 zustand 역시 마찬가지이다.

 

아래 예제를 한 번 살펴보자.

countStore.ts

const useCountStoreBase = create<TCountStore>()(
  devtools((set, get) => ({
    count: 0,

    actions: {
      increase: () => set((state) => ({ count: state.count + 1 })),
      decrease: () => set((state) => ({ count: state.count - 1 })),
      getCount: () => get().count,
    },
  }))
)

이렇게 스토어가 정의되어 있다고 해보자.

CountView.tsx

import { useCountStore } from '@/store/countStore'
import { useCallback, useEffect } from 'react'

const CountButton = () => {
  const { increase, decrease } = useCountStore.use.actions()

  return (
    <>
      <button onClick={increase}>증가</button>
      <button onClick={decrease}>감소</button>
    </>
  )
}

const Count = () => {
  const count = useCountStore.use.count()
  const { getCount } = useCountStore.use.actions()

  const callCount = useCallback(() => {
    console.log('count', count)
    console.log('getCount', getCount())
  }, [])

  useEffect(() => {
    callCount()
  }, [count])

  return <div>{count}</div>
}

export default function CountView() {
  return (
    <>
      <Count />
      <CountButton />
    </>
  )
}

좀 말도 안 되는 예제이기는 하지만 get().count로 가져올 때랑 그냥 state로 가져올때랑 어떻게 차이가 나나 설명하기 위한 예제이다. useCallback에 대해서는 굳이 설명하진 않겠다.

자 만약 저런 식으로 Count 컴포넌트가 구현이 되어있다면 콘솔에 count와 getCount 값이 어떻게 찍히게 될까?

증가 3회, 감소 2회

 

react에서 useState로 상태값을 관리할 때도 만약 최신값이 필요할 때 useRef를 활용하고는 한다.

zustand 역시 state값으로 최신값을 못 가져오는 상황이 발생하면 get()을 활용해 주면 최신값을 가져와 활용할 수 있다.

반응형


댓글

TOP