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?
3
Answers
For props React uses shallow comparison. Which just like you wrote means that for objects, it’s determined by if the object memory reference is the same.
Here is an article about it more in detail.
So in your case, where
getData
returns a new reference, the child component would re-render even though it has the same fields and values.You could use useMemo hook to avoid re-rendering issue.
By default, React will re-render your component because the
data
prop’s reference changes even if the values are the same but you can useReact.memo
with a custom comparison function.React.memo
will prevent re-rendering of Component unless the values of a or b in the data object change.