DEV Community

Discussion on: Sharing Context with React Portals

Collapse
 
bmmpt profile image
Bruno Mendonca • Edited

What about?

  return (
    <div>
      <ImportantValueProvider>
        <ComponentA />
      </ImportantValueProvider>
      <Modal>
        <ComponentB />
      </Modal>
  )
Enter fullscreen mode Exit fullscreen mode

In this case they are in different trees and cant share context or can they?

Collapse
 
mickmister profile image
Michael Kochell

Libraries that export a Modal component are usually using a Portal under the hood. In this case, you do need that <Modal> inside of the <ImportantValueProvider>. There's no way around it.

Your Provider should be at the top of your application, unless you have multiple instances of the same kind of Provider, which is sort of an anti-pattern unless you have a niche use case that fits it. In short, put your Provider at the top-level of your app and you should be good to go.