Rendering is the most important procedure that a programmer has to manage in frontend development. In React, the render() method is the only required method in a class component, and is responsible for describing the view to be rendered to the browser window. Coupled with the clever way that React operates around its virtual DOM concept, there are certain subtleties in how this method works, and understanding them will greatly benefit any aspiring React developer.

Throughout this writing, I will reference this codepen for a demonstration of discussed behaviors.

1. render() 101

First of all, render() is not user callable. It is part of the React component lifecycle and is called by React at various app stages, generally when the React component is first instantiated, or when there is a new update to the component state. Render does not take any arguments, and returns a JSX.Element which contains the view hierarchy of the current component. This view hierarchy will later be translated into HTML and displayed in the browser window.

As mentioned before, render() is not user callable as it is an event that happens in the component’s lifecycle. With that said, if it is absolutely necessary to manually render the view, you can instead call the built-in class method forceUpdate(). Keep in mind that this is considered an  anti-pattern . If you were designing sensible React components, its state and props changes should naturally control the render process, and you should never feel the need to make a manual call.

Within the lifecycle, these are the scenarios where render is called:

  • After the React component is first instantiated, following the constructor() call.
  • After an update to the component’s props
  • After a setState() call

If you have the Codepen opened at this point, before anything is rendered you will see 2 alert messages from the browser: “render() is called in Parent component!”, and “render() is called in Child component!”. These messages are invoked from the corresponding render() methods of the example’s parent and child component. They serve to introduce the first case of render() invocation: when the component is first instantiated.

Once the set of alerts is dismissed, a very simple UI will render:

Example UI

#javascript #node #react #render #function #method #dom #virtual dom

Understanding React Rendering
1.30 GEEK