Saturday, April 27, 2024

React - You should avoid passing object as a prop

Consider these two objects:


obj1 = {


    fname:"Arun", 


    lname:"kumar"

}


obj2 = {

    fname:"Arun", 

    lname:"kumar"

}


Are these equal? They are not!

 

That's why in React, it is advised to avoid passing an object as a prop in components. If you do, the component will re-render even if you change nothing in the prop values!

 

 In React, it is recommended to avoid passing an object as a prop in components. If you do pass an object as a prop, the component will re-render every time the object changes, even if the changes don't affect the component.


<Component user={obj1} />  => unnecessary re-render

 

<Component fname={obj1.fname} lname={obj1.lname} /> => re-renders only when fname or lname has any changes compared to its previous value.

No comments:

Post a Comment