Next.js, Redux toolkit, next-redux-wrapper 연동하는 방법 feat. typescript

남양주개발자

·

2022. 1. 30. 20:05

728x90
반응형

Next.js Redux toolkit next-redux-wrapper 연동하는 방법 feat. typescript

버전

  • next@^12.0.8
  • next-redux-wrapper@^7.0.5
  • @reduxjs/toolkit@^1.7.1

Next.js에서 SSR(Server Side Rendering), SSG(Server Side Generation)를 사용할 때 next-redux-wrapper 라이브러리를 활용해서 redux 스토어를 간편하게 연동할 수 있습니다.

next-redux-wrapper 설치

yarn add next-redux-wrapper

redux toolkit을 활용해서 스토어를 생성할 때 아래와 같이 next-redux-wrapper로 스토어 생성 함수를 감싸줍니다.

import { configureStore, combineReducers, AnyAction } from "@reduxjs/toolkit";
import production from "features/production";
import { createWrapper, HYDRATE } from "next-redux-wrapper";
import { FindCastCrewState } from "features/production/findCastCrew/findCastCrewSlice";

export type State = {
  findCastCrew: FindCastCrewState;
};

const reducer = (state: State, action: AnyAction): State => {
  switch (action.type) {
    case HYDRATE:
      return action.payload;

    default: {
      const combineReducer = combineReducers({
        ...production,
      });
      return combineReducer(state, action);
    }
  }
};

const store = configureStore({
  reducer,
});

const createStore = () => store;

export type RootState = ReturnType<typeof reducer>;
export type AppDispatch = typeof store.dispatch;

const wrapper = createWrapper(createStore);

export default wrapper;

일반적으로 사용되는 Provider를 사용는 것이 아닌 앱 컴포넌트를 wrapper.withRedux로 감싸줍니다.

// _app.tsx
import wrapper from "app/store";
...
export default wrapper.withRedux(MyApp);

페이지 컴포넌트에서 리덕스 스토어가 필요할 경우 아래와 같이 wrapper로 감싸주기만 하면 스토어에 접근할 수 있습니다.

import wrapper from "app/store";

export const getStaticProps: GetStaticProps = wrapper.getStaticProps(
  (store) => () => {
    return {
      props: {
        value: 1,
      },
    };
  },
);

Next.js getStaticProps에서 스토어에 접근할 수 있는 것을 확인할 수 있습니다. wrapper를 사용해서 getServerSideProps도 동일하게 처리할 수 있습니다.

728x90
반응형
그리드형

💖 저자에게 암호화폐로 후원하기 💖

아이콘을 클릭하면 지갑 주소가자동으로 복사됩니다