Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the React.addons.batchedUpdates API?

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()?

like image 885
Josh Haberman Avatar asked Nov 16 '14 04:11

Josh Haberman


1 Answers

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 ...
    })
});
like image 123
David Tinker Avatar answered Nov 16 '22 06:11

David Tinker