2. x2beeStore
이 문서는 Next.js 프로젝트에서 상태를 관리하기 위한 x2beeStore를 사용하는 방법을 안내합니다.
첫번째 단계에서 파일을 생성하여 상태를 정의하고, 두번째 단계에서 정의한 상태를 저장하고 조회하는 방법을 안내합니다.
Zustand 사용법은 매우 간단하지만 상태를 생성할 때 반복되는 코드를 줄이기 위해 x2beeStore를 제공합니다.
x2beeStore 사용방법
1
파일 생성 및 상태 정의
아래 코드는 testStore.ts 파일을 생성하고 x2beeStore를 사용하여 상태를 관리하는 예제입니다.
import x2beeStore from '@/lib/common/plugins/x2beeStore';
export const testState = {
test1: '',
test2: '',
test3: '',
};
const useTestStore = x2beeStore('testStore', testState);
export default useTestStore;위 코드와 같이 x2beeStore를 import하고, testState처럼 객체를 정의합니다.
그리고 x2beeStore 함수를 사용하여 상태 저장소를 생성하고, 초기 상태로 testState 객체를 사용하여 useTestStore 변수에 할당합니다.
2
상태 저장 및 조회 예제
다음은 testStore 상태를 저장하고 조회하는 예제 컴포넌트입니다.
'use client';
import useTestStore from '@/lib/common/stores/testStore';
const TestPage = () => {
function setStore() {
useTestStore.setState({
test1: '11111',
test2: '22222',
test3: '3333'
});
}
function getStore() {
const store = useTestStore.getState();
console.log(store);
}
return (
<>
test2222
<button onClick={() => setStore()}>상태 저장</button>
<button onClick={() => getStore()}>상태 조회</button>
</>
);
};
export default TestPage;useTestStore라는 이름으로 testStore.ts 파일에서 생성한 상태 저장소를 가져옵니다.
setStore와 getStore 함수 예제를 바탕으로 상태를 저장하고 조회할 수 있습니다.
마지막 업데이트