React re-renders on state change - right?

I recently had a piece of state that was like this:

const [myState, setMyState] = useState([]);

where we would update the array whenever an item was selected - with these changes affecting the CSS and thus being reflected in the element.

However, we wanted to extend the component to be able to deal with multiple items and so the state was changed to an object of arrays:

const [myState, setMyState] = useState({ key1: [], key2: [] });

To update a state that is an object you generally have to make a copy of the object like so:

const obj = myState;
obj[key] = [...obj[key], newItemToAppend];
setMyState(obj);

This change however led to the component not re-rendering until some other event fired. So what's going on?

Well when we copy the object like this we are copying the reference. React doesn't see this as a change, since the ref to the object isn't being changed - only it's contents.

We can fix this by deep copying the object

const obj = JSON.parse(JSON.stringify(myState));
obj[key] = [...obj[key], newItemToAppend];
setMyState(obj);

All rights reserved © Joshua Bosman 2025