Large number of React roots on a page v single React root

(Ajay Sagar) #1

Hi React folks, hoping to get some advice on what I think is an unusual pattern in React (but useful for my scenario). I am looking to render a large tree with multiple levels and 1000s of vertices. Each vertex would be a pretty non trivial component in itself, with text, images etc. I would like to render each vertex as a child of the DOM node that contains the parent, which will let me do things like toggle visibility/apply transforms using CSS to the parent which will be inherited by all its descendants. To add some further complexity, I would like to move children around to different parents dynamically, based on user actions. To support this, instead of changing the state of the old/new parents and re-rendering (what could be potentially large subtrees) from scratch, I have been looking to implement re-parenting outside React, without getting in its way.

What I have come up with is to use a Container - Presentational component pattern, where the container returns null for the initial render() but in componentDidMount() I can manually create a DOM element for mounting (and append it as a child of the parent and which I can later move around). Then when the state is changed to e.g. “expanded”, I return a stateless sub-component from render(), using Portals like so: return ReactDOM.createPortal(<View {…this.props.viewProps} />, this.viewContainer). I guess I could also implement a similar strategy by making my Container component tree just a regular js tree object (like some kind of tree store) and I can dispatch events to the required object in the tree and have it also render the stateless Presentational component. The only way I see to do this is to do something like this: ReactDOM.render(<View {…viewProps} />, domNode) which I guess would create a React root per vertex in my tree. I have a few questions about this scenario:

  1. Does this pattern make sense at all in the context of what I am looking to do :slight_smile: . I am looking to avoid re-renders due to the sheer volume of nodes as mentioned earlier, are there alternative approaches to do the same thing ?
  2. Coming to the topic of the question, is there any difference between using Portals to get everything to render under a single root and creating a new react root per vertex.

Looking forward to your thoughts, thanks!