React setState Merge

This is a retraction. I was a bit unfair to React’s setState function earlier because I didn’t understand it. I didn’t realize that setState would merge new properties in the object you return. So, for example, setState({prop: “apple”}) merges the new value of prop into the state object. It overwrites the value of prop but leaves other properties unchanged. If I understand correctly, setState actually does mutate the state object. According to the docs, it performs a “shallow merge”. The docs are pretty clear. I’m not sure how I came to misunderstand this API. Soon I’ll review my existing React apps to clean up code that was written with this misunderstanding.

That said, I prefer the method encouraged by Redux—immutable state objects that get replaced every time. I need to learn Redux better. Right now I’m writing a widget in React that offers a demonstration of a blockchain (kinda). Maybe this will turn into an opportunity to study Redux in more depth.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s