Updating with React.render

Ah, the all powerful function that starts it all. But what exactly does it do?

To the source

Our investigation starts with the function itself, ReactMount.render.

In pseudo-English
  • First, validate the inputs
  • If there was no previous component, render as a new component.
  • Otherwise, compare the next component to the previous component using shouldUpdateReactComponent.
  • If shouldUpdateReactComponent is true, update the component using ReactComponent.updateComponent. Otherwise, unmount and continue to render as a new component.

Déjà vu?

This is very similar to the update algorithm between render passes. Just take a look at ReactCompositeComponent._updateRenderedComponent. The key here again is shouldUpdateReactComponent.

When you call React.render on a node that already has a mounted component, React effectively perform its diff algorithm, albeit with a single component. Here is an example using React.render's updates. We can confirm this by seeing how state is maintained across renders.

React.render gives you a declarative way to use React's update flow at the top level, similar to how re-rendering works inside a component. Many times, however, you can create a wrapper component so that you only have a single React.render call. This allows you to keep the logic inside components, which may be cleaner.

Hack?

Notice how you can take advantage of React's virtual DOM updates without creating any component classes!

_
Read Another

Fade-in Image

Want an easy way to make your images a little more graceful? This recipe is for an Image component that fades in once the image is loaded. You can see it in action here.

Liked this?

Subscribe

Subscribe for a range of articles from React basics to advanced topics such as performance optimization and deep dives in the React source code.