Member-only story

Unlocking the Power of ...: Why Spread Operator is Essential in Updating Object and Array States with useState Hook

Vinodh Thangavel
2 min readJul 12, 2023

Array and object state should be updated little differently, due to the way equality operator works for the object and array in javascript


export default function App() {

const [names, setNames] = useState(['initial']);

const addNames = () => {

const temp = names;
temp.push('test');
setNames(temp);

};

console.log('render');

return (
<div>
<p> {names}</p>
<button onClick={addNames}>Add Names </button>
</div>
);
}

even though state is updated, it is not reflected in ui, because re-render doesn’t happen

Here on click of the button we are pushing a new value to temp and updating the state value with the temp value, but it is not reflect in UI because of re-render doesn’t happened

A component will re-render when its state or props are changed, but even though we have changed the state, it is not re-render, that is because of mystery behind equality operations in array.

Equality operations in array will check the references not the values in the array, so since the reference value is same like before, react consider the names state is unchanged still.

That is exact reason that we need to create a new array to create new reference in the memory and send it as a new state, which will make react…

--

--

Vinodh Thangavel
Vinodh Thangavel

Written by Vinodh Thangavel

Passionate lifelong learner, coding enthusiast, and dedicated mentor. My journey in tech is driven by curiosity, creativity, and a love for sharing knowledge.

No responses yet