Introduction: From Redux to Redux Toolkit
Welcome back and thank you for joining me in this tutorial If you have been a developer for React application particularly, those built with Next.js then you must be privy to some challenges you might have encountered concerning state management. Wouldn’t you know it, Redux, a predictable container for application state, has been a popular solution for some time. However, maintaining Redux store is not easy and initial setup can be quite frustrating. Now there is Redux Toolkit (RTK), an improved version aimed at reducing the difficulties of working with Redux but at the same time, preserving its advantages. In this post, I will be explaining how to integrate Redux Toolkit for low coupling of state management in Next.js applications beyond the RTK setup.
Why Redux Toolkit for Next.js?
- Simplified Setup: Less boilerplate code.
- Improved State Management: Efficient slice management.
- Enhanced Async Handling: Seamless integration with
createAsyncThunk. - Better Compatibility: Optimized for Next.js’s SSR and SSG capabilities.
Setting Up Redux Toolkit in Your Next.js Project
npm install @reduxjs/toolkit react-redux
# or
yarn add @reduxjs/toolkit react-redux
Creating State Slices with createSlice
features/userSlice.js:
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
user: null,
status: 'idle',
};
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
setUser(state, action) {
state.user = action.payload;
},
setStatus(state, action) {
state.status = action.payload;
},
},
});
export const { setUser, setStatus } = userSlice.actions;
export default userSlice.reducer;
Managing Async Operations in Next.js with createAsyncThunk
features/userApi.js:
import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
export const fetchUser = createAsyncThunk(
'user/fetchUser',
async (userId) => {
const response = await axios.get(`https://api.example.com/users/${userId}`);
return response.data;
}
);
Configuring the Store for Next.js with configureStore
store.js:
import { configureStore } from '@reduxjs/toolkit';
import userReducer from './features/userSlice';
import { fetchUser } from './features/userApi';
const store = configureStore({
reducer: {
user: userReducer,
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(),
});
export default store;
Integrating with Next.js Pages and Components
_app.js:
import { Provider } from'react-redux';
import store from '../store';
function MyApp({ Component, pageProps }) {
return (
<Provider store={store}>
<Component {...pageProps} />
</Provider>
);
}
export default MyApp;
components/UserComponent.js:
import React from'react';
import { useSelector, useDispatch } from'react-redux';
import { fetchUser } from '../features/userApi';
const UserComponent = () => {
const dispatch = useDispatch();
const user = useSelector((state) => state.user);
const handleClick = () => {
dispatch(fetchUser('123'));
};
return (
<div>
{user? (
<div>User: {user.name}</div>
) : (
<button onClick={handleClick}>Fetch User</button>
)}
</div>
);
};
export default UserComponent;
Best Practices for Redux Toolkit in Next.js
- Keep Slices Modular
- Leverage
createAsyncThunkfor Async Operations - Optimize Store Configuration
- Utilize
react-reduxHooks for Component Integration
Conclusion
By integrating Redux Toolkit into your Next.js project, you’ve significantly streamlined your state management workflow. This setup not only simplifies development but also enhances the maintainability and scalability of your application.
Finally, for more such updates and to read more about such topics, please follow our LinkedIn page Frontend Competency.