1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

redux-toolkitをnextjsアプリに導入する

1
Posted at

現状reactやnextでアプリを作成するときの状態管理としてreduxを利用することが多いが、redux-toolkitを使うと実装が簡単であった。

redux-toolkitをインストール

導入したいプロジェクトにインストール
npm install @reduxjs/toolkit

sliceを作成する

redux-toolkitはsliceの中でactionとreducerを同時に書くことができる。

今回は例として、ユーザー情報を管理するauthSliceを作成する

authSlice.ts
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

export const authSlice = createSlice({
//sliceの名前
  name: "auth",
//初期値を設定
  initialState: {
    myprofile: {
      profile_id: "",
      nickname: "",
      profileUser: "",
      image: "",
    },
  },
  reducers: {
    setMyprofile(state,action) {
      state.myprofile = action.payload
    },
  },

//reducerをエクスポートし、コンポーネント内で使えるようにする
export const {
  setMyprofile
} = authSlice.actions;

//コンポーネント内のuseSelectorで呼び出せるようにする
export const selectProfile = (state) => state.auth.myprofile;

export default authSlice.reducer;

storeを作成する

store.tsを作成して、作成したsliceをstore内で呼び出す。

store.ts
import { configureStore } from "@reduxjs/toolkit";
import authReducer from "../features/auth/authSlice";


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

## _app.tsxでstoreを呼び出す
ComponetntをProviderで囲み、storeを適用する。

```_app.tsx
import "../styles/globals.css";
import type { AppProps } from "next/app";
import { store } from "../src/app/store";
import { Provider } from "react-redux";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  );
}

export default MyApp;

```

あとは通常のreduxの時と同様に呼び出したいコンポーネントで
useSelectorやuseDispatchを使ってstoreにアクセスすることができる。
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?