Redux Explained

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.

Advantages of Redux

Where did Redux come from?

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.

Three Core Principles of Redux

When is it appropriate to use Redux?

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.

Understanding Key Redux Concepts

State

The state is all the information stored at a particular point in time. Redux manages the state centrally for the entire application.

Store

The Redux store is a JavaScript object with methods such as getState(), dispatch(action), and subscribe(listener).

Actions

Actions are JavaScript objects with a type property that describes what should happen in the application.

Reducers

Reducers are pure functions that take the current state and an action, returning the new state.

Middleware

Middleware allows you to handle side effects like logging or making asynchronous API requests.

Thunks

Thunks allow dispatching functions instead of plain objects, enabling asynchronous operations in Redux.

Step-by-Step Example

Follow these steps to set up Redux in a project.

Project Setup

Create a new project folder and install Redux:

mkdir redux_project
cd redux_project
npm init -y
npm install redux

Creating the Store

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;

Dispatching Actions

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' });

Real-World Usage

Redux is commonly used in large-scale applications where multiple components require access to shared state, such as:

Further Exploration

To dive deeper into Redux, explore these topics:

Resources