Organizing the React render method


One common way to organize React render methods is to split the returned JSX into several smaller pieces, which are then assembled in the final JSX before returning. This makes the overall structure of the render function easier to understand. Note that the objective isn't to obtain JSX fragments we can reuse elsewhere, we just want our JSX to be split into bite-size, one-off sections that have a clear function in the component markup.

Now, look at the two examples of a simple render method below. Which one would you use?



Both approaches yield the same result and you would be tempted to use stateless components here, as the resulting all-JSX return statement looks better. But using stateless components defined inside your render method is a big no-no. Why? Because they will be re-rendered to the DOM from scratch every time the parent container renders.

Keep in mind how reconciliation works. It will traverse your JSX tree, adding and removing nodes as needed. If a component instance stays the same, its render method will generate some jsx which will be compared to the old jsx to figure what changes to the DOM are needed. And here is the problem: since we are defining the component inside the render method, it will in effect be a new component every time render is invoked. This means the DOM for its previous instance will be discarded and replaced by a new (potentially identical..) DOM tree. This can be a significant performance hit, and it defeats the entire purpose of reconciliation.

TL;DR: do not define stateless react components inside the render method of another component.

Comments

Popular posts from this blog

Parallel Beam Tracing and Visualization of 200 Million Sonar Points

Parallel Gaussian Elimination Using MPI

Flickering 2D transform elements in Chrome: a simple fix