How to Use Redux with MERN Stack
The MERN stack — MongoDB, Express.js, React, and Node.js — is a popular combination for building full-stack JavaScript applications. While React alone provides powerful state management with hooks and Context API, applications with complex state logic, global data needs, or deeply nested components often benefit from a dedicated state management library like Redux.
Integrating Redux with MERN helps manage state consistently across your React frontend, especially when dealing with data fetched from your Node.js/Express API backed by MongoDB.
Here’s a step-by-step guide on how to use Redux in your MERN applications:
Set Up Your MERN App
Assume you already have your MERN app running, with:
A backend REST API built using Express and Node.js that connects to MongoDB.
A React frontend created using Create React App or similar setup.
Install Redux and Related Packages
In your React frontend directory, install Redux, React-Redux (to connect Redux to React), and Redux Toolkit (recommended for simpler, cleaner code):
npm install @reduxjs/toolkit react-redux
Redux Toolkit simplifies store setup, reduces boilerplate, and provides Create Your Redux Store
Inside your React project (e.g., in src/store.js), create your store using Redux Toolkit’s configureStore:
import { configureStore } from '@reduxjs/toolkit';
import yourReducer from './features/yourSlice';
const store = configureStore({
reducer: {
yourData: yourReducer,
},
});
export default store;
Create a Redux Slice
Create a slice to handle specific state logic — for example, managing user data fetched from your Express API. In src/features/yourSlice.js:
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';
export const fetchUsers = createAsyncThunk(
'yourData/fetchUsers',
async () => {
const response = await axios.get('/api/users'); // API endpoint in Express
return response.data;
}
);
const yourSlice = createSlice({
name: 'yourData',
initialState: {
users: [],
status: 'idle',
error: null,
},
reducers: {},
extraReducers: (builder) => {
builder
.addCase(fetchUsers.pending, (state) => {
state.status = 'loading';
})
.addCase(fetchUsers.fulfilled, (state, action) => {
state.status = 'succeeded';
state.users = action.payload;
})
.addCase(fetchUsers.rejected, (state, action) => {
state.status = 'failed';
state.error = action.error.message;
});
},
});
export default yourSlice.reducer;
Connect Redux to React App
In src/index.js, wrap your React app with Redux’s <Provider> and pass in the store:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
Use Redux State and Dispatch in Components
In your React components, use useSelector to read Redux state and useDispatch to trigger actions:
import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchUsers } from './features/yourSlice';
const UserList = () => {
const dispatch = useDispatch();
const { users, status } = useSelector((state) => state.yourData);
useEffect(() => {
dispatch(fetchUsers());
}, [dispatch]);
if (status === 'loading') return <p>Loading...</p>;
if (status === 'failed') return <p>Failed to fetch users.</p>;
return (
<ul>
{users.map((user) => (
<li key={user._id}>{user.name}</li>
))}
</ul>
);
};
export default UserList;
Conclusion
Redux brings powerful, predictable state management to your MERN stack applications. By combining Redux with React, and syncing state with your Express API, you create a scalable architecture perfect for large-scale, data-driven web apps.
Learn MERN Stack Training Course
Read More:
CRUD Operations Using MERN Stack
Building a To-Do App Using MERN Stack
Authentication in MERN Stack Using JWT
React Router DOM: Simplifying Navigation
Visit Quality Thought Training Institute
Comments
Post a Comment