0

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?

  • You already have the answer. Build a new object (which will have a new reference, which is what React uses to check if state has updated). `setObject({...object, value: object.value + 1})` – windowsill Jan 23 '22 at 03:47
  • you can refer here: https://plnkr.co/edit/O0krzXvdZn1XjuXS?open=Hello.js&deferRun=1, @windowsill has stated the point correctly. – Oo-_-oO Jan 23 '22 at 04:00

0 Answers0