Redux is a JavaScript framework for managing the frontend state of a web application. It allows us to store information in an organized manner in a web app and to quickly retrieve that information from anywhere in the app. Redux is modeled on a few previous web technologies including Elm and Flux.
Redux was created by Dan Abramov in 2015 as an experiment to create a simplified version of Flux. He aimed to remove unnecessary boilerplate code and enhance debugging capabilities by introducing time-traveling dev tools.
Redux is ideal for applications with complex state management needs. While React’s Context API is sufficient for simple state management, Redux provides scalability, middleware support, and powerful developer tools.
The state is all the information stored at a particular point in time. Redux manages the state centrally for the entire application.
The Redux store is a JavaScript object with methods such as getState(), dispatch(action), and subscribe(listener).
Actions are JavaScript objects with a type property that describes what should happen in the application.
Reducers are pure functions that take the current state and an action, returning the new state.
Middleware allows you to handle side effects like logging or making asynchronous API requests.
Thunks allow dispatching functions instead of plain objects, enabling asynchronous operations in Redux.
Follow these steps to set up Redux in a project.
Create a new project folder and install Redux:
mkdir redux_project
cd redux_project
npm init -y
npm install redux
Create a file store.js:
const { createStore } = require('redux');
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;
}
}
const store = createStore(counterReducer);
module.exports = store;
Create a file index.js:
const store = require('./store');
store.subscribe(() => console.log(store.getState()));
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'INCREMENT' });
store.dispatch({ type: 'DECREMENT' });
Redux is commonly used in large-scale applications where multiple components require access to shared state, such as:
To dive deeper into Redux, explore these topics: