Is it OK to use React.render() multiple times in the DOM?

Reactjs

Reactjs Problem Overview


I want to use React to add components multiple times throughout the DOM. This fiddle shows what I'm looking to do, and it doesn't throw any errors. Here's the code:

HTML:

Reactjs Solutions


Solution 1 - Reactjs

Yes, it is perfectly fine to call React.render multiple times on the same page. Just as you've suggested, the React library itself is only loaded once, but each call to React.render will create a new component instance independent of any others. (In fact, such a situation is not uncommon on sites that are in the process of transitioning to React, where some portions of the page are generated using React.render and others are not.)

Solution 2 - Reactjs

This approach is ok from a page load performance point of view, but there are other downsides and multiple React roots should be avoided if possible.

  • Different React roots cannot share context, and if you need to communicate between the React roots, you will need to fall back on global DOM events
  • You get less benefit from performance optimizations like time slicing - suspense and async rendering. It's not possible to suspend across React root boundaries

Further reading

Solution 3 - Reactjs

If you were wondering if it's ok to use ReactDOM.render() multiple times with the same container, the docs say: "If the React element was previously rendered into [the same] container, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYPCrumbleView Question on Stackoverflow
Solution 1 - ReactjshopperView Answer on Stackoverflow
Solution 2 - ReactjsYangshun TayView Answer on Stackoverflow
Solution 3 - ReactjsDavidView Answer on Stackoverflow