Redux Thunk is a middleware that allows you to write asynchronous logic. In Next.js, as data fetching is done on both the server and client, Redux Thunk can be employed to execute API requests, side effects and async state updates.
1. Install the necessary dependencies. npm install @reduxjs/toolkit react-redux redux-thunk
2. Create your Redux store and add thunk middleware.
import { configureStore } from "@reduxjs/toolkit";
import thunk from "redux-thunk";
import taskReducer from "./taskSlice";
export const store = configureStore({
reducer: {
tasks: taskReducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(thunk),
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
3. Define an async thunk action.
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
export const fetchTasks = createAsyncThunk("tasks/fetchTasks", async () => {
const response = await fetch("/api/tasks");
return response.json();
});
const taskSlice = createSlice({
name: "tasks",
initialState: {
tasks: [],
loading: false,
},
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchTasks.pending, (state) => {
state.loading = true;
})
.addCase(fetchTasks.fulfilled, (state, action) => {
state.loading = false;
state.tasks = action.payload;
});
},
});
export default taskSlice.reducer;
4. Provide the store to your Next.js app. Wrap _app.tsx (for pages router) or layout.tsx (for app router) in a provider.
import { Provider } from "react-redux";
import { store } from "../redux/store";
export default function App({ Component, pageProps }) {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
5. Use redux-thunk inside your component.
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { fetchTasks } from "../redux/taskSlice";
const TaskList = () => {
const dispatch = useDispatch();
const { tasks, loading } = useSelector((state) => state.tasks);
useEffect(() => {
dispatch(fetchTasks());
}, [dispatch]);
return (
<div>
{loading ? (
<p>Loading...</p>
) : (
tasks.map((task) => <p key={task.id}>{task.name}</p>)
)}
</div>
);
};
export default TaskList;
Redux Thunk in Next.js enables efficient handling of asynchronous actions such as API calls within Redux. It comes in handy for keeping an application state global and dealing with side effects, rendering your app scalable and easier to maintain.
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our ReactJS Expertise.