DEV Community

Cover image for What I learned : Immutability as I understand it.
Snap Dragon
Snap Dragon

Posted on

What I learned : Immutability as I understand it.

An immutable data type can be defined as one where the data cannot be changed. A new copy of the data type is returned with the altered data instead. Immutability is a very important concept in react. In order to re render a component react checks to see if state has changed by comparing the memory location of the old and new state object. If the memory locations are different , react determines that the state has changed and re renders the component. This is why its extremely important to change the contents of a state object in an immutable way instead of mutating the object.

import "./styles.css";
import {useState} from 'react'

export default function Shelf() {

  const [shelf, setShelf] = useState([]);
  const [book, setBook] = useState("");

  function handleFormSubmit(e){
    e.preventDefault();

    //Update shelf state in an immutable way to trigger 
    // a re render.
    setShelf([...shelf,book]);

  }

  return (

    <>
        <form onSubmit={handleFormSubmit}>
          <label htmlFor="book">Book: </label>
            <input type="text" id="book" value={book} onChange={(e)=> setBook(e.target.value)}/>

        </form>
        <ul className="App">
          {shelf.map((book,index)=><li key={index}>{book}</li>)}
        </ul>
    </> 
  );
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)