소개
Next.js는 React 프레임워크로, 서버 사이드 렌더링(SSR)과 정적 사이트 생성을 지원합니다. Zustand는 경량 상태 관리 라이브러리로, 간단하고 직관적인 API를 제공합니다. 이 두 가지를 결합하면 강력한 상태 관리와 효율적인 SSR 하이드레이션을 구현할 수 있습니다
학습 내용
Zustand 설정
- 스토어 생성: createCounterStore를 사용하여 상태 관리 스토어를 초기화합니다.
import create from 'zustand';
const createCounterStore = (set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
decrease: () => set((state) => ({ count: state.count - 1 })),
});
export const useCounterStore = create(createCounterStore);
- 초기 상태 설정: defaultInitState를 사용하거나 initCounterStore로 동적으로 설정합니다.
const defaultInitState = { count: 0 };
const initCounterStore = (initialState = defaultInitState) => create(set => ({
...initialState,
increase: () => set(state => ({ count: state.count + 1 })),
decrease: () => set(state => ({ count: state.count - 1 })),
}));
Provider 구성
- 글로벌 상태 관리: CounterStoreProvider를 src/app/layout.tsx에 추가합니다.
import { CounterStoreProvider } from './stores/CounterStore';
function MyApp({ Component, pageProps }) {
return (
<CounterStoreProvider initialState={pageProps.initialState}>
<Component {...pageProps} />
</CounterStoreProvider>
);
}
export default MyApp;
- 동적 초기 상태: 필요시 initialState를 CounterStoreProvider에 전달합니다
<CounterStoreProvider initialState={{ count: 10 }}>
<MyComponent />
</CounterStoreProvider>
SSR 및 하이드레이션
- 일관성 유지: 서버에서 초기 상태를 계산하여 클라이언트와 동기화합니다.
export async function getServerSideProps() {
const initialState = { count: 5 };
return { props: { initialState } };
}
결과 및 배운 점
Next.js와 Zustand를 결합하면 효율적인 상태 관리와 SSR 하이드레이션을 구현할 수 있습니다. 이는 클라이언트와 서버 간의 일관성을 유지하고 초기 렌더링 성능을 향상시키는 데 도움이 됩니다.
참고 사이트
https://docs.pmnd.rs/zustand/guides/nextjs#initializing-the-store
Zustand Documentation
Zustand is a small, fast and scalable bearbones state-management solution, it has a comfy api based on hooks
docs.pmnd.rs
https://docs.pmnd.rs/zustand/guides/ssr-and-hydration
Zustand Documentation
Zustand is a small, fast and scalable bearbones state-management solution, it has a comfy api based on hooks
docs.pmnd.rs
'TIL' 카테고리의 다른 글
TIL - Next.js 클라이언트 컴포넌트에서 API 토큰 관리 문제 트러블 슈팅 (0) | 2024.07.12 |
---|---|
TIL - 효율적인 데이터 Fetching 전략: 벌크 vs 개별 요청 (0) | 2024.07.11 |
TIL- 시스템 설계와 Many-to-Many 관계 적용 (0) | 2024.07.09 |
TIL - 서버 사이드 렌더링으로 화면 깜빡임 제거 (0) | 2024.07.08 |
TIL - 소셜 로그인 기능 추가 도중 트러블 슈팅 (0) | 2024.07.06 |