react.js - Render on requestAnimationFrame

Kosmetika picture Kosmetika · Jan 10, 2015 · Viewed 8.3k times · Source

I want to experiment with performance of some React components inside my app. I know that ClojureScript's Om framework (https://github.com/swannodette/om) uses some optimization techniques like using immutables with implementing shouldComponentUpdate() and rendering on requestAnimationFrame change.

Is there plain JavaScript mixin that could introduce rendering based on requestAnimationFrame?

Answer

Michelle Tilley picture Michelle Tilley · Jan 10, 2015

This is possible if you use something like Browserify or webpack to build React from a CommonJS environment, or otherwise produce a custom build of React. That is to say, you can't do this if you just use the downloadable, pre-built React.

Check out Pete Hunt's react-raf-batching project for a more comprehensive solution (including rAF polyfills), but here's a minimal example to get this working:

var ReactUpdates = require("react/lib/ReactUpdates");

var rafBatchingStrategy = {
  isBatchingUpdates: true,
  batchedUpdates: function(callback, param) {
    callback(param);
  }
};

var tick = function() {
  ReactUpdates.flushBatchedUpdates();
  requestAnimationFrame(tick);
};

requestAnimationFrame(tick);

ReactUpdates.injection.injectBatchingStrategy(rafBatchingStrategy);