Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must React components be in hierarchy?

I have always been told that React components should be designed in a tree hierarchy so that the ancestor/parents can hold the state and pass it to their children.

I just wonder, is that a MUST?

The design principal of React is that "React has been designed from the start for gradual adoption, and you can use as little or as much React as you need." I just thought what if I have an existing project, and I want to add a bit of React components separately here and there without modifying most of the existing HTML/code? Can these components still communicate with one another?

For instance, let's say I want to add two separate React components at different positions in an existing plain HTML page, and I really like existing HTML to be non-Javascript generated/modified as it is. The two components are not in any hierarchy with each other. Can they still access each other's state? If one component gets updated (be it by user's click, AJAX response, etc), can this component notify the other to update itself or tell it to call a function?

I haven't tried anything yet, but I would have thought if I were really going to do the above, I would use global variables/functions as the last resort if nothing else works. However, I am more interested in learning any React-conventions/methods/best practice to achieve the above.

like image 822
user2526586 Avatar asked Dec 07 '25 02:12

user2526586


1 Answers

If you had to share the state (only with React, at least), you'd have to wrap these components in a context and then render them on those separate places with Portals. I'm pretty sure that is doable, although it doesn't really answer your question, in this case the two components would be siblings that have a common parent, context provider.

A more reasonable solution would be to use e.g. Redux or similar solution. You'd have a single store and then you'd just call ReactDOM.render as many times as you want for each component that you want to mount somewhere on the page. Each of these components would have to be a child of a store provider (which is also a component) and then these components would be able to communicate through the store.

like image 50
paolostyle Avatar answered Dec 08 '25 16:12

paolostyle