D DevBrainBox

React Redux

Redux is an open-source JavaScript library for managing and centralizing application state.

What is Redux?

React-Redux is a popular state management library that helps manage the application state in React applications.

Why Do We Need Redux?

As React apps grow, managing state between multiple components becomes complex. Props drilling (passing props through multiple layers) can become hard to maintain.

Redux solves this by:

  • Centralizing state in a single global store.
  • Making state predictable via a strict pattern: Actions → Reducers → Store → UI.
DevBrainBox

Concepts of React-Redux

DevBrainBox
ConceptDescription
StoreThe single object that holds the state of your whole app
ActionA plain JS object that describes what happened
ReducerA pure function that takes current state and action, and returns new state
DispatchA method used to send an action to the store
SelectorA function to get specific data from the state

Install Redux packages

npm install @reduxjs/toolkit react-redux

React Redux Example 1

  • Stores a username in Redux state.
  • Allows changing the username using a form input.

Create Redux Store

//store.js (src/store/store.js)

import {createSlice, configureStore} from '@reduxjs/toolkit'

let userSlide = createSlice({
    name: 'user',
    initialState: {name: 'Rohit Sharma'},
    reducers:{
        setName: (state, action) => {
            state.name = action.payload
        }
    }
})

export let {setName} = userSlide.actions

let store = configureStore({
    reducer: {
        user: userSlide.reducer
    }
})

export default store;

Provide Store in App

// index.js

import { Provider } from 'react-redux'
import store from './store/store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
   <Provider store={store}>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </Provider>
);

Access and Update Username

// App.js

import React, { useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { setName } from './store/store';

function App() {
   let username = useSelector((state) => state.user.name)
  let dispatch = useDispatch()
  let [input, setInput] = useState('')

  function handleChange() {
    console.log('changes input')
    dispatch(setName(input));
    setInput('')
  }

  return (
        <h1>{username}</h1>
        <input value={input} onChange={(event) => setInput(event.target.value)} />
        <button onClick={handleChange}>Submit</button>
  );
}

export default App;
  • State managed via Redux Toolkit.
  • useSelector and useDispatch used to read and update state.

React Redux Example 2

  • Add items to a todo list and remove them

Access and Update Username

// src/store.js

import { configureStore, createSlice } from '@reduxjs/toolkit';

const todoSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    addTodo: (state, action) => {
      state.push({ id: Date.now(), text: action.payload });
    },
    removeTodo: (state, action) => {
      return state.filter(todo => todo.id !== action.payload);
    }
  }
});

export const { addTodo, removeTodo } = todoSlice.actions;

const store = configureStore({
  reducer: {
    todos: todoSlice.reducer,
  },
});

export default store;

Wrap App with Provider

// src/index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import App from './App';
import store from './store';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <App />
  </Provider>
);

App Component – Add & Remove Todos

//src/App.js

import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { addTodo, removeTodo } from './store';

function App() {
  const todos = useSelector((state) => state.todos);
  const dispatch = useDispatch();
  const [task, setTask] = useState('');

  const handleAdd = () => {
    if (task.trim() !== '') {
      dispatch(addTodo(task));
      setTask('');
    }
  };

  return (
    <div style={{ padding: '30px', maxWidth: '400px', margin: 'auto' }}>
      <h2>Todo List (Redux)</h2>
      <input
        type="text"
        placeholder="Enter todo"
        value={task}
        onChange={(e) => setTask(e.target.value)}
      />
      <button onClick={handleAdd} style={{ marginLeft: '10px' }}>Add</button>

      <ul>
        {todos.map((todo) => (
          <li key={todo.id} style={{ marginTop: '10px' }}>
            {todo.text}
            <button
              onClick={() => dispatch(removeTodo(todo.id))}
              style={{ marginLeft: '10px', color: 'red' }}
            >
              X
            </button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;
  • Add a todo using the input and button.
  • Delete any todo by clicking the "X" next to it.
  • All state is handled via Redux.