티스토리 뷰

728x90

현재 진행중인 Next.js 프로젝트에서 데이터 패칭 연결 중 문제가 발생했다.

각 페이지에서 공통적으로 사용해야 하는 데이터가 존재한다는 것!!!!

지저분한 코드를 작성하다 상태 관리 라이브러리를 사용하기로 결정했고 이번 기회에 배워보고 싶었던 "zustand"를 선택했다.

 

🐾 설치하기

# NPM
npm install zustand

 

 

🐾 스토어 생성하기

create 함수를 사용해 스토어를 생성한다.

// 공식 문서 예제
import { create } from 'zustand'

const useStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
  updateBears: (newBears) => set({ bears: newBears }),
}))

 

create 함수의 콜백은 set, get 매개변수를 가지며 이를 통해 상태를 변경하거나 조회할 수 있다.

  • get 함수를 호출 -> 상태와 액션을 가진 스토어 객체(state)를 얻을 수 있음
  • set 함수를 호출 -> 상태를 변경할 수 있음. set 함수를 호출할 때 콜백을 사용하면 get 함수를 사용하지 않아도 바로 스토어 객체(state)를 얻을 수 있음

 

 

🐾 구성 요소를 바인딩하기

provider 없이도 어디에서나 훅을 사용할 수 있다.

상태를 선택하면 해당 상태가 변경될 때 컴포넌트가 다시 랜더링된다. <- 상태는 반응형이기 때문

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>
}

 

 

프로젝트에서는 stadium과 place_name을 전역 상태로 사용하였다.

여기서 상태는 페이지가 새로고침을 하더라도 유지되어야 하기 때문에 persist를 사용해 스토리지에 상태 값을 저장했다.

  • persist: zustand 상태를 저장소에 저장해 데이터를 유지할 수 있도록 돕는 미들웨어
import { StadiumType } from '@/types/stadium';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

export type Stadium = StadiumType

export type StadiumStore = {
  selectedStadium: Stadium | null; 
  setSelectedStadium: (stadium: Stadium) => void; 
};

export const useStadiumStore = create(
  persist<StadiumStore>(
    (set) => ({
      selectedStadium: null,
      setSelectedStadium: (stadium) => set({ selectedStadium: stadium }),
    }),
    {
      name: 'stadium-storage',
    }
  )
);

 

 

728x90