Open In App

React JS Immutability

Improve
Improve
Like Article
Like
Save
Share
Report

In a React class component, immutability is crucial for state updates. In the provided Todo example, the AddTodo function attempts to modify the state by pushing todos directly, but without immutability practices, it fails to trigger the expected re-renders.

Prerequisites:

Reason behind immutability in React:

In React, objects are identified by reference, not by their values. To mutate the state correctly, it’s essential to use immutability. Instead of directly modifying the state, create a new object, incorporate the desired changes, and set the component’s state using that new object. This ensures proper state updates.

Steps to Create React Application And Installing Module:

Step 1: Creating React Application And Installing Module.

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command.

cd foldername

Project structure :

Example: Below is the code example of the above explained approach.

Javascript




//App.js
import "./App.css";
import Todos from "./Components/Todos";
 
function App() {
    return (
        <div className="App">
            <Todos />
        </div>
    );
}
 
export default App;


Javascript




import React, { Component } from "react";
 
export class Todos extends Component {
    constructor(props) {
        super(props);
        this.state = {
            todos: [" "],
            newTodoText: "",
        };
    }
 
    textFunc = (e) => {
        this.setState({ newTodoText: e.target.value });
    };
 
    AddTodo = () => {
        const { newTodoText, todos } = this.state;
        let newTodos = [...todos];
 
        // Check if the new todo already exists in the array
        if (newTodos.includes(newTodoText)) {
            alert("Task already exists!");
        } else {
 
            if (newTodoText !== " ") {
                newTodos.push(newTodoText);
                this.setState({ newTodoText: "" });
            }
 
            this.setState({ todos: newTodos });
            console.log("Todos in the AddTodo function", this.state.todos);
        }
    };
 
    render() {
        console.log("Todos in the render()", this.state.todos);
 
        return (
            <div>
                <h2>Today's Todos :</h2>
                <input
                    type="text"
                    placeholder="  Add Your Task"
                    onChange={this.textFunc}
                    value={this.state.newTodoText}/>
                {this.state.todos.map((todo, idx) => (
                    <div key={idx}>
                        <h4> {todo}</h4>
                    </div>
                ))}
                <button onClick={this.AddTodo}>
                    Add todo
                </button>
            </div>
        );
    }
}
 
export default Todos;


CSS




/* App.css */
body {
    text-align: center;
    background-color: antiquewhite;
}
 
button {
    width: 10rem;
    height: 1.8rem;
    border: none;
    background-color: rgb(227, 222, 222);
    border-radius: 8px;
    transition: all 0.3s ease-in;
}
 
button:hover {
    background-color: rgb(201, 196, 196);
}
 
input {
    background-color: rgb(244, 244, 244);
    width: 20rem;
    height: 1.5rem;
    border-radius: 8px;
    border: none;
    font-size: medium;
    font-weight: 500;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}


Step to run the application : Run the development server by the following command.

npm start

Output:

todo'sGIF

Output



Last Updated : 14 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads