This simple issue has puzzled me for the last days and I can't seem to find an answer.
Question: Why is my Child
component not re-rendering when I click the button?
const Child = ({ data }) => {
return (
<div>
<span>{data.value}</span>
</div>
)
}
const Parent = () => {
const [object, setObject] = useState({ value: 0 })
const handleClick = () => {
setObject(o => {
const newObject = o
newObject.value += 1
return newObject
})
console.log(object)
}
return (
<div>
<button onClick={handleClick}>Click me!</button>
<Child data={object} />
</div>
)
}
I know it has to do with the prop value being passed being an object and React not deep comparing the object to trigger a re-render. But what would be a good pattern here? I would like to keep my data organised in objects.
I can work around the issue by ensuring I set my state to a new object instead of a reference to the same by changing my click handler function to const newObject = { ...o }
. But is there a better pattern here?