State callbacks in React

Emil Ong
Haus Engineering Blog
2 min readApr 11, 2016

This a very quick post to highlight a feature in React that is frequently overlooked (at least by me 😊). The setState(), replaceState(), and forceUpdate() methods of React.Component all take an optional callback function that is called when a state “transaction” is completed. Note the implication here (supported by explicit documentation) is that setState() and replaceState() are not synchronous updates of the state.

One thing that was not obvious from the documentation is that these callbacks are called with no arguments, but with this set to the component instance. Given that your callback will be called once the state manipulations are done, having this set gives you access to a consistent view of the instance’s state.

What’s it good for?

If you want to provide a way for users of your component to get access to the state upon its changes, these callbacks are quite useful. Thus far, the only example I’ve seen is react-router’s onUpdate prop, which is currently implemented as taking the injected prop and setting that as the setState() callback whenever the router state changes. Thus you could access the router location on each change like so:

The react-ga documentation shows one way to use this approach for integrating react-router with Google Analytics.

Alternative uses

If you look at the way the onUpdate API from react-router is implemented above you might, as I have done, thought this approach gives a lot of access to a callback via the instance reference. However, that doesn’t mean that the setState() callback is useless, even in this API.

react-router might be able to tighten the interface above to pass the current this.state.location or even this.state.location.pathname to the onUpdate prop as an argument. It doesn’t require the callback, but if there were several places in the component that might change the same bit of state and the callback processing was somewhat complicated, you could DRY up that processing by having all such setState() calls call the same callback to format and publish the state to subscribers.

If you’re interested in working with us, discussing issues like these and others, please check out our jobs page and get in touch!

--

--