Open In App

What are the Benefits of using Immutable Data in Redux ?

In Redux, immutable data means that once you create the state, you can't directly change it. Instead, whenever you need to update the state, you create a new state object. This keeps your original state safe and offers benefits like predictability, easier debugging, and performance optimizations. In this article, we make a project that implements an Undo/Redo functionality and shows the use case of an immutable state in Redux.

Benefits of Immutable Data in Redux

Approach

Steps to Create Application

Step 1: Create React Application named redo-undo-app and navigate to it using this command.

npx create-react-app undo-redo-app
cd undo-redo-app

Step 2: Install required packages and dependencies.

npm install  react-redux @reduxjs/toolkit

Updated dependencies

All required dependencies required for project will look like in package.json file.

"dependencies": {
"@reduxjs/toolkit": "^2.2.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-redux": "^9.1.0",
},

Project Structure

project-structure

Project Structure

Example: To demonsrtate creating an immutable data in redux which can be controlled by using redux.

/* App.css */

.App {
    text-align: center;
}

button {
    background-color: rgb(203, 207, 202);
    padding: 10px 20px;
    border: 1px solid black;
    cursor: pointer;
}

button:hover {
    background-color: green;
}

input {
    padding: 10px 20px;
    border: 1px solid black;
}
// store.js

import { createSlice } from "@reduxjs/toolkit";
import { configureStore } from "@reduxjs/toolkit";

const itemSlice = createSlice({
    name: "Item",
    initialState: {
        past: [],
        present: null,
        future: [],
    },
    reducers: {
        addItem: (state, action) => {
            state.past.push(state.present);
            state.present = action.payload;
            state.future = [];
        },
        undo: (state) => {
            const previous = state.past.pop();
            if (previous) {
                state.future.unshift(state.present);
                state.present = previous;
            }
        },
        redo: (state) => {
            const next = state.future.shift();
            if (next) {
                state.past.push(state.present);
                state.present = next;
            }
        },
    },
});

export const { addItem, undo, redo } = itemSlice.actions;

export default configureStore({
    reducer: itemSlice.reducer,
});
// App.js

import "./App.css";
import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { undo, addItem, redo } from "./store";

function App() {
  const dispatch = useDispatch();
  const { future, past, present } = useSelector((state) => state);
  const [item, setItem] = useState("");

  const addItemHandle = () => {
    if (!item) return;
    dispatch(addItem(item));
    setItem("");
  };
  return (
    <div className="App">
      <img
        src="https://media.geeksforgeeks.org/gfg-gg-logo.svg"
        alt="gfg_logo"
      />
      <div>
        <input
          type="text"
          value={item}
          onChange={(e) => setItem(e.target.value)}
        />
        <button onClick={addItemHandle}>Add Item</button>
        <div>
          <h2>Current Item: {present}</h2>
          <button onClick={() => dispatch(undo())} disabled={past.length === 0}>
            Undo
          </button>
          <button
            onClick={() => dispatch(redo())}
            disabled={future.length === 0}
          >
            Redo
          </button>
        </div>
      </div>
    </div>
  );
}

export default App;
// index.js 

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

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

Step to Run the Application:

To run application, go to redo-undo-app and enter this command.

npm start 

Output:

Final Output of Undo-Redo-app

Final Output of Undo-Redo-app

Article Tags :