D Dev Notebook

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. 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.
dev notebook

Concepts of React-Redux

dev notebook
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 { configureStore, createSlice } from '@reduxjs/toolkit';

const userSlice = createSlice({
  name: 'user',
  initialState: { name: 'John Doe' },
  reducers: {
    setName: (state, action) => {
      state.name = action.payload;
    },
  },
});

export const { setName } = userSlice.actions;

const store = configureStore({
  reducer: {
    user: userSlice.reducer,
  },
});

export default store;

Provide Store in App

// 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/store';

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

Access and Update Username

// App.js

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

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

  const handleChange = () => {
    dispatch(setName(input));
    setInput('');
  };

  return (
    <div style={{ padding: '20px' }}>
      <h1>Redux Username Example</h1>
      <p><strong>Current Username:</strong> {username}</p>
      <input
        type="text"
        value={input}
        placeholder="Enter new name"
        onChange={(e) => setInput(e.target.value)}
      />
      <button onClick={handleChange} style={{ marginLeft: '10px' }}>
        Change Username
      </button>
    </div>
  );
}

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.