DEV Community


Discussion on: 3 Mistakes Junior Developers Make with React Function Component State

thawkin3 profile image
Tyler Hawkins Author

Thanks, good suggestion! How's something like this:

As far as I understand it, the simplest way to explain why data should be immutable in React is that React components are functions of props and state, so when the diffing algorithm is deciding whether or not to update the UI for any given component, it compares the previous props and state with the current props and state.

So if you mutate the previous state, the comparison between the previous state and the current state will actually show that it's the same object reference with the same data, so it will incorrectly see that there's nothing new to show.

thomasburleson profile image
Thomas Burleson

To paraphrase your reply.
1) Immutability means data modifications will result in new instances; so explicit comparisons are supported and deep-comparisons can be avoided.
2) The setter function also implicitly triggers the FC to asynchronously re-render. Without the setter, the data would be updated, but the FC would not redraw to reflect the current data state.