본문 바로가기

TIL

TIL - Next.js와 Zustand를 사용한 상태 관리 및 SSR 하이드레이션

소개

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