Home > Software design >  Why react re-renders component if the object reference is the same?
Why react re-renders component if the object reference is the same?

Time:12-12

I know that we use spread operator to make an exact copy of an existing object but with new reference so that react will re-render component. But I didn't get that why actually we don't need to use spread operator in this case:

import {useState } from 'react';

function Users() {
  const [obj1, setObj]=useState({name: "User_1"});

  const obj2={name: "User_2"}

  const clicked =()=> {

    obj2.name=`User_${2 Math.random()}`;
    setObj(obj2);
  }

  return (
    <div>
      <button onClick={clicked}>{obj1.name}</button>
    </div>
    );
}
  
export default Users;

I know that in the first click it should be updated because reference is changed to the new array(from obj1 to obj2) but I thought after first click it wouldn't render anymore because reference is the same(from obj2 to again obj2) but to my surprise it updated actually. I want to know the reason behind it since it got me confused.Thanks in advance for any help!

CodePudding user response:

const obj2={name: "User_2"}

Every time the component renders, this line makes a brand new object. The variable name (obj2) may be the same, but it's a new reference to a new object. So each time you set state, you're setting it to a different object than is currently in state, which means the component rerenders.

  • Related