こちらを参考にしました。
next.js + typescript で Redux Toolkit を使う最小サンプル
Next.js + Redux Toolkit
プロジェクトの作成
npx create-next-app ex01 --ts
cd ex01
yarn add @reduxjs/toolkit react-redux
yarn dev
プログラム
pages/index.tsx
// ---------------------------------------------------------------
// index.tsx
//
// ---------------------------------------------------------------
import { useDispatch, useSelector } from "react-redux";
import { counterSlice, CounterState, store } from "./_app";
import { NextPage } from "next";
// ---------------------------------------------------------------
const Home: NextPage = () => {
const dispatch = useDispatch();
const selector = useSelector((state: CounterState) => state);
const { increment, decrement } = counterSlice.actions;
return (
<div>
<p>Hello World!</p>
<p>{store.getState().counter.value}</p>
<button onClick={() => { dispatch(increment()); }} > Plus </button>
<button onClick={() => { dispatch(decrement()); }} > Minus </button>
<p>Jun/27/2022 PM 14:55</p>
</div>
);
};
export default Home;
// ---------------------------------------------------------------
pages/_app.tsx
// ---------------------------------------------------------------
// _app.tsx
//
// ---------------------------------------------------------------
import React from "react";
import type { AppProps } from "next/app";
import { Provider } from "react-redux";
import { configureStore, createSlice } from "@reduxjs/toolkit";
// ---------------------------------------------------------------
export type CounterState = {
value: number;
};
// ---------------------------------------------------------------
const initialState: CounterState = { value: 0 };
// ---------------------------------------------------------------
export const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment(state) {
state.value++;
},
decrement(state) {
state.value--;
},
},
});
// ---------------------------------------------------------------
export const store = configureStore({
reducer: {
counter: counterSlice.reducer,
},
});
// ---------------------------------------------------------------
function MyApp({ Component, pageProps }: AppProps) {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
export default MyApp;
// ---------------------------------------------------------------
ブラウザーで、 http://localhost:3000/ にアクセス