5

The React v0.12 release announcement included the following:

New Features:

* React.addons.batchedUpdates added to API for hooking into update cycle

However I cannot find any documentation for this API. What is its purpose?

Specifically, any chance that it has an equivalent of Ember.run()?

2 Answers 2

7

When responding to synthetic events like onClick and so on, component state changes are batched so lots of calls to this.setState for the same component will only result in one render.

If you are changing state in response to some other async callback (e.g. AJAX or setTimeout) then every call to this.setState will result in a render. You can wrap your work in batchedUpdates(..) to avoid this.

var React = require('react/addons');
var batchedUpdates = React.addons.batchedUpdates;
var request = require('superagent'); // AJAX lib

var req = request('GET', ...).end(function(err, res) {
    // invoked when AJAX call is done
    batchedUpdates(function(){
        .. all setState calls are batched and only one render is done ...
    })
});
1
  • Thank you for this. I was accepting keyboard events from Mousetrap.js and was wondering why state change batching wasn't working. This answered my question and provided the solution.
    – Raman
    Jun 23, 2015 at 22:16
0

The default batched update strategy is great for your average website. Sometimes you have extra requirements and need to deviate from that.

The initial reason this was made public is for a requestAnimationFrame batching strategy, which is better for games and sites that need to update often and in many places.

It's just an extensibility point to solve edge case issues.

2
  • Does it include an equivalent of Ember.run()? ie. a way to batch updates outside of React's normal event loop? Nov 16, 2014 at 7:03
  • React has a default way to batch updates which iirc uses setTimeout. This allows you to specify an alternative, or get data, analytics, etc. out of it. Without knowing more about Ember.run, I'd guess it's similar.
    – Brigand
    Nov 17, 2014 at 2:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.