react.js - Render on requestAnimationFrame
Asked Answered
F

1

9

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?

Francklin answered 10/1, 2015 at 14:44 Comment(0)
R
9

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);
Raul answered 10/1, 2015 at 18:13 Comment(2)
Note there are a few (solveable) corner cases you might want to handle: github.com/petehunt/react-raf-batching/issues/8Junket
As of the writing of this comment, npm install react-raf-batching requires a peer of react 0.9 and current version is 0.14.5 so it's no longer a quick install. I haven't tried if it just needs minor tweaking or something more involved.Cranium

© 2022 - 2024 — McMap. All rights reserved.