score:1

Accepted answer

react portals is what i was looking for.

as per my question, i wanted to have same context for all the components mounted at different locations (dom nodes).

portals solved exactly this issue. now, i can have one context component housing all the components that exist on that page. like this:

const dashboardcontextdom = document.getelementbyid('dashboard-root');

const comp1dom = document.getelementbyid('comp1-root');
const comp2dom = document.getelementbyid('comp2-root');

const dashboard = () => {
   return (
      <>
        {reactdom.createportal(<component1 />, comp1dom)}
        {reactdom.createportal(<component2 />, comp2dom)}
      </>
   );
}

if(dashboardcontextdom) {
   reactdom.render(<dashboard />, dashboardcontextdom);
}

with these components housed in one context allows to easily pass state from one component to another via prop drilling and lifting state up.

score:0

you have two options with react:

  1. move component 1 and component 2 and their state into a parent component, and pass the parent's update state function to them:
componentwrapper {
...
const updatestate = () => {
    //update state
}

return (
    <component 1 updateparentstate={updatestate}/>
    <component 2 updateparentstate={updatestate}/>
)
...
}
  1. you cannot update the state of a component that is not a parent or a child without using an external state management solution, such as redux or the new usecontext api/hook. these libraries involve moving all individual component's states to a larger centralized global state, which can be updated and accessed by all components.

Related Query

More Query from same tag