리액트 zustand

안녕하세요·2024년 3월 29일
0

react

목록 보기
19/32

프로젝트에서 pagenation에 쓰이는 currentpage 를 리덕스 툴킷을 사용했었는데
zustand가 간편하다 해서 간단하게 사용해봤습니다.

폴더 구조와 파일 설정

프로젝트의 src 폴더 안에 store 폴더를 생성하고, 그 안에 currentPageStore.js 파일을 만들었습니다. 이 파일에서는 현재 페이지 번호를 관리하는 Zustand 스토어를 생성합니다.

import {create} from 'zustand';

const usePageStore = create(set => ({
  currentPage: 1,
  changePage: (target) => set({ currentPage: target }),
}));

export default usePageStore;

//currentPageStore.js

스토어 사용하기

스토어를 사용하기 위해서는 먼저 usePageStore 훅을 임포트한 후, 필요한 상태(currentPage)와 함수(changePage)를 추출해 사용합니다.

import usePageStore from './store/currentPageStore';
  const { currentPage,changePage } = usePageStore();

  onChange={page => changePage(page)}
  
  

이 방식을 사용하면, changePage 함수를 호출하여 어느 컴포넌트에서든지 쉽게 currentPage 상태를 업데이트할 수 있습니다.

0개의 댓글