Friday, November 29, 2024
Google search engine
HomeLanguagesReactJS Immutability

ReactJS Immutability

ReactJS Immutability: This concept is important for updating any object in react and the component state depends on it. Let’s understand it with an example. The code given below considers the Todo component, it is a class-based component that has a state todos which is an array representing the todo items. There is an arrow function AddTodo which will push two todos in the state. And in the render function, we are displaying the todos. It also has a button that will trigger the AddTodo function. Also, note we did not bind the function as while using arrow functions react takes care of it. Apparently in this case the expected output should be that when we click on the button the array should get mutated and re-render the Todo component as we are changing the state in the function by adding two todos to the list. But the component does not re-render even if we click the button single or multiple times.

Reason why this happens: In react, objects are identified by their reference and not by the value they hold. So it becomes necessary to use a predefined method ( while mutating the state ) by creating a different object first of initial data, adding new data by which we want to mutate to the new object, and then finally set the state of the component to the new object. You can refer to the code below.

Step1: Creating React Application And Installing Module.

npx create-react-app foldername

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

cd foldername

Step3: After creating the ReactJS application, run the development server by the following command.

npm start

Project structure :

Step4: Create a components folder in src and create a Todos.js file in it. Don’t forget to import it to the App.js file.

Step5: Add the following code in the Todo.js file. Here we have created a class-based component and has a todos state which is an array.

Javascript




import React, { Component } from "react";
  
export class Todos extends Component {
  constructor(props) {
    super(props);
    this.state = {
      todos: ["Wake up at 6am", "Get Fresh"
              "DSA at gfg (6:30am - 8 am)"],
    };
  }
  AddTodo = () => {
    this.state.todos.push(" College ( 9am - 4 pm ) ");
    this.state.todos.push(" badminton (6 - 7 pm) ");
    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>
        {this.state.todos.map((todo, idx) => (
          <div key={idx}>
            <h4> {todo}</h4>
          </div>
        ))}
        <button onClick={this.AddTodo}>Add todo</button>
      </div>
    );
  }
}
  
export default Todos;


Step 6: App.js file

App.js




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


Output:

Web app on initial render

Web app on clicking the button twice

Explanation: As we can see the state is being mutated and the todos are being added to the list. But it’s just the fact that react compares the previous state and initial state by reference and not by value.

Correct method: Also note that mutating state directly is not advisable we should use the this.setState() method to mutate the state.

Javascript




import React, { Component } from "react";
  
export class Todos extends Component {
  constructor(props) {
    super(props);
    this.state = {
      todos: ["Wake up at 6am", "Get Fresh",
              "DSA at gfg (6:30am - 8 am)"],
    };
  }
  AddTodo = () => {
    let newTodos = [...this.state.todos];
    newTodos.push(" College ( 9am - 4 pm ) ");
    newTodos.push(" badminton (6 - 7 pm) ");
  
    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>
        {this.state.todos.map((todo, idx) => (
          <div key={idx}>
            <h4> {todo}</h4>
          </div>
        ))}
        <button onClick={this.AddTodo}>Add todo</button>
      </div>
    );
  }
}
  
export default Todos;


Correct output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments