Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React component re-rendering when object is a prop

If I have a component say- <Component /> which acceps props as data={a:1, b:2} which is created after some custom operation lets say that operation is performed by a function getData() which returns this data object.

Now this component re-renders and again getData returns us data={a:1, b:2} as props.

Now will my <Component /> update on UI? as the memory location of both the props is different but their properties are same?


Now if i have useEffect in this component which is

useEffect(()=>{
   someFunction();
},[data])

this useEffect will trigger for each render if data is {a:1, b:2} but reference is different? for the case I mentioned above.

like image 721
meg Avatar asked May 31 '26 16:05

meg


1 Answers

By default, React will re-render your component because the dataprop's reference changes even if the values are the same but you can use React.memo with a custom comparison function.

import React from 'react';

const Component = React.memo(({ data }) => {
  
  return <div>{data.a}, {data.b}</div>;
}, (prevProps, nextProps) => {
  
  return prevProps.data.a === nextProps.data.a && prevProps.data.b === nextProps.data.b;
});

React.memo will prevent re-rendering of Component unless the values of a or b in the data object change.

function ParentComponent() {
  const data = getData();
  return <Component data={data} />;
}
like image 96
GifftyCode Avatar answered Jun 02 '26 06:06

GifftyCode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!