Next.js 13 RTK 사용하기

버건디·2023년 7월 10일
1

Next.js

목록 보기
41/52
post-thumbnail
post-custom-banner

1. RTK 설치하기

npm install @reduxjs/toolkit react-redux

2. src/redux/store.ts 파일에서 configureStore 생성

import { configureStore } from "@reduxjs/toolkit";

export const store = configureStore({
  reducer: {},
});

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

3. src/redux/hooks.ts 파일 생성 후 셋팅

import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";

export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

4. src/redux/Providers.tsx 생성 후 Provider 컴포넌트 불러오기

"use client";

import React from "react";
import { Provider } from "react-redux";
import { store } from "./store";

type Children = {
  children: React.ReactNode;
};

export default function Providers({ children }: Children) {
  return (
    <>
      <Provider store={store}>{children}</Provider>
    </>
  );
}

use client 를 사용해서 layout.tsx 에서도 불러올수 있도록 한다.

5. layout.tsx에서 Providers로 감싸주기

     <body suppressHydrationWarning={true}>
        <script
          dangerouslySetInnerHTML={{
            __html: themeInitializerScript,
          }}
        ></script>
		// 감싸주기
        <Providers>
          <Card>
            <Header />
            <ContentCard>{children}</ContentCard>
            <Foorter />
            <div id="portal"></div>
          </Card>
        </Providers>
      </body>

6. src/redux/features 폴더에 사용할 slice 만들어주기

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  bpm: 60,
};

export const bpmSlice = createSlice({
  name: "bpm",
  initialState,
  reducers: {
    changeBpm: (state, action) => {
      state.bpm = action.payload;
    },
  },
});

export const { changeBpm } = bpmSlice.actions;

7. store.ts 에서 slice 불러오기

import { configureStore } from "@reduxjs/toolkit";
import { bpmSlice } from "./features/bpmSlice";

export const store = configureStore({
  reducer: {
    bpm: bpmSlice.reducer,
  },
});

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

8. 사용할 컴포넌트에서 불러오기

import { useDispatch, useSelector } from "react-redux";
import { changeBpm } from "@/redux/features/bpmSlice";
import { RootState } from "@/redux/store";

...

  const dispatch = useDispatch();
  const bpmFromRedux = useSelector((state: RootState) => state.bpm.bpm);
profile
https://brgndy.me/ 로 옮기는 중입니다 :)
post-custom-banner

1개의 댓글

comment-user-thumbnail
2023년 9월 15일

GOOD 👍

답글 달기