Logo

How to Use Redux with Next.js and TypeScript

📌 **Prerequisites**: Basic Next.js with TypeScript setup.

🔧 Step 1: Install Redux Toolkit and React Redux

1npm install @reduxjs/toolkit react-redux

📁 Step 2: Create the store

1// store/store.ts
2import { configureStore } from "@reduxjs/toolkit";
3import counterReducer from "./counterSlice";
4
5export const store = configureStore({
6  reducer: {
7    counter: counterReducer,
8  },
9});
10
11export type RootState = ReturnType<typeof store.getState>;
12export type AppDispatch = typeof store.dispatch;

🧩 Step 3: Create a counter slice

1// store/counterSlice.ts
2import { createSlice } from "@reduxjs/toolkit";
3
4interface CounterState {
5  value: number;
6}
7
8const initialState: CounterState = { value: 0 };
9
10const counterSlice = createSlice({
11  name: "counter",
12  initialState,
13  reducers: {
14    increment: (state) => { state.value += 1; },
15    decrement: (state) => { state.value -= 1; },
16  },
17});
18
19export const { increment, decrement } = counterSlice.actions;
20export default counterSlice.reducer;

🪢 Step 4: Wrap your app with the Redux `<Provider>`

1// pages/_app.tsx
2import type { AppProps } from "next/app";
3import { Provider } from "react-redux";
4import { store } from "@/store/store";
5
6export default function App({ Component, pageProps }: AppProps) {
7  return (
8    <Provider store={store}>
9      <Component {...pageProps} />
10    </Provider>
11  );
12}

📦 Step 5: Use Redux in your components

1// components/Counter.tsx
2import { useSelector, useDispatch } from "react-redux";
3import { RootState, AppDispatch } from "@/store/store";
4import { increment, decrement } from "@/store/counterSlice";
5
6const Counter = () => {
7  const count = useSelector((state: RootState) => state.counter.value);
8  const dispatch = useDispatch<AppDispatch>();
9
10  return (
11    <div>
12      <p>Count: {count}</p>
13      <button onClick={() => dispatch(increment())}>+</button>
14      <button onClick={() => dispatch(decrement())}>-</button>
15    </div>
16  );
17};
18
19export default Counter;

🎯 Redux is now set up in your Next.js TypeScript app!