Imagine a React Component like this with two states, each can be updated with the click of a button:
The object-like state foo with the update function setFoo
The number state bar with the update function setBar
The component might look like this:
export function Component() {
const [foo, setFoo] = useState({"foo": 0})
const [bar, setBar] = useState(0)
const handleClick = useCallback(() => {
const f = foo
f.foo += 1
setFoo(f)
}, [foo, setFoo])
return (
Foo: {foo.foo}
Bar: {bar}
)
}
Calling setBar causes the component will re-render and show the new bar value.
By contrast, updating foo with setFoo does not trigger a re-render, and only when bar is later updated does the correct foo value appear.
Why does updating an object-type state not trigger a re-render?