Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react.js - Render on requestAnimationFrame

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?

like image 335
Kosmetika Avatar asked Jan 10 '15 14:01

Kosmetika


People also ask

Does react use requestAnimationFrame?

React doesn't currently use requestAnimationFrame to do DOM updates (as we call it, the "batching strategy"). The batching strategy is injectible though so it's possible to use something else.

Why should I use requestAnimationFrame?

To optimize system and browser resources, it is recommended to use requestAnimationFrame , which requests the browser to execute the code during the next repaint cycle. This allows the system to optimize resources and frame-rate to reduce unnecessary reflow/repaint calls.

What is requestAnimationFrame Javascript?

requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.


1 Answers

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);
like image 144
Michelle Tilley Avatar answered Oct 05 '22 17:10

Michelle Tilley