Using React.js to improve speed of your Angular app

If you came into troubles with speed of real-time updates in your Angular app and have no angular-like way out, perhaps you should consider using a React component on the problematic part. Recently, I wrote an introduction to the framework and I think you should try it out!

When to use React in my Angular app

  • when doing DOM updates often,  better when only smart part of data changes
  • when your ng-repeat is laaarge and even better if its two-dimensional
  • when you have too much watchers in your scope and you can’t remove them, but they are completely unuseful for the real-time rendering. Nuff said – $scope.$digest is too expensive
  • you want to *control when *the component should be re-rendered.

Angular way

Let’s imagine that we have a real-time component in our app, which takes too much resources. Data comes through websocket and are changed each 0.5 sec,  but not all of them. We are using ng-repeat with track-by to make it as fast as possible. Changes are asynchronoes via websocket, so we are forced to use $scope.$digest to make changes happen in view.

Lets see how our app looks with Angular. First, there is a controller that creates data a attach it to the scope. In real world, the data would be updated with service, but I am keeping it simple.

Every one second, some random items in array are updates. Then, we have a template which renders our data:

React way

First of all, we need to create a component that will represent a row in our expensive-to-render row:

Another way is to create a component for each cell in the table. This aproach is better in my opinion, because of code resusablity. The another benefit of this approach is, that we can use the shouldComponentUpdate() method in the Cell component, to even ommit creating and diffing virtual DOM of the component, when we dont have to.

Then, we have to create a container, the component will render into, instead angular template:

As you can see, React component markup is a bit longer and more complicated (on first sight) than Angular way.

Ok, now when we have our component ready, we need to mount it and update from the controller, like so:

Please notice, that using document.getElementById is not the safest method when using Angular, as we cant be sure if the partial template is already compiled. The better approach is to use some directive, and mount a React component in the directive’s link method. For now, we can keep it simple in this demo.

That’s it! You can check without react and with react examples. Try to scroll the content and watch for freezing of the screen every second, when browser updates the DOM.

You can find source code at github.