Code, Shiny Things, and Other Random Shit I Like

TIL: React does what react wants

React… A great way to use javaScript to have a panic attack.

So i couldn’t figure out why using state to keep ‘score’ in a game wasn’t quite triggering a ‘game over’ event - even though the game was clearly over.

The reason:

React updates the state whenever its good and goddamned ready.

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

The problem:

React updates the state whenever its good and goddamned ready.

Aka. shit acts funny if you are using logic based on state values.

The solution:

setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.

Aka Use a Callback, Sucker.

Oh. It’s also day 15 of my 100daysofcode. weee.