DEV Community

Cover image for React States works by Reference
Suyash Vashishtha
Suyash Vashishtha

Posted on

React States works by Reference

Today I learned something cool in React. I was trying to update a post in the list of Posts ( State ) but even after changing the element's key value, it wasn't reflecting in UI ( but showing updated data in the console log. I spent hours trying to figure out why it is happening and according to JS, I was doing the right array manipulation.

So I did some research and a GitHub thread finally guided me to the right track, comes out that the React States are used by references not by value.

"React compares by reference, in the setState(newState) call, you are just setting the state to the same list. Changing the contents of the list doesn't change the reference to the list. When the next state is the same as the old state, React bails out on doing any work.
One quick thing you can do is slice the array like this:

const newData = oldData.slice(0);
newData[0] = 'something'
setState(newData);
"

GitHub Thread

Here slice() returns a new array based on the given condition, so it breaks the state reference and creates a new array reference. Now React will take the new array as a different entity and will update the state.

React is a beautiful thing ❤️

Top comments (2)

Collapse
 
naucode profile image
Al - Naucode

Hey, that was a nice read, you got my follow, keep writing 😉

Collapse
 
suyashdev profile image
Suyash Vashishtha

Thank mate ❤️