Redux is a powerful state management library that helps manage application state in a predictable way. It is particularly useful for complex applications where multiple components need to share state. In this tutorial, we will explore how Redux works, when to use it, and how to integrate it into a React application.
Redux follows a unidirectional data flow, ensuring a predictable state management pattern. The core concepts of Redux are:
Redux is ideal for applications where:
Ensure you have Node.js installed, then create a React project and install Redux dependencies:
npx create-react-app redux_example
cd redux_example
npm install redux react-redux
Create a store.js file inside the src folder:
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(rootReducer);
export default store;
Then, wrap your application with the Provider component in index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
ReactDOM.render(
,
document.getElementById('root')
);
Define actions in actions.js:
export const increment = () => ({ type: 'INCREMENT' });
export const decrement = () => ({ type: 'DECREMENT' });
Create a reducer in reducers.js:
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
export default counterReducer;
Use the useSelector and useDispatch hooks in a React component:
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement } from './actions';
const Counter = () => {
const count = useSelector(state => state.count);
const dispatch = useDispatch();
return (
Count: {count}
);
};
export default Counter;
Install the Redux DevTools extension and configure the store:
import { createStore } from 'redux';
import rootReducer from './reducers';
const store = createStore(
rootReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
Use the browser window object for debugging:
window.store = store;
Then, in the browser console, check the current state with:
console.log(window.store.getState());
Redux requires returning a new state object instead of modifying the existing state. This ensures React re-renders correctly.
Incorrect:
state.count += 1; return state;
Correct:
return { ...state, count: state.count + 1 };
Redux is a powerful tool for managing complex application state. With practice, you’ll gain confidence in using it effectively!