Ritesh Shakya
Ritesh Shakya

Reputation: 585

How to Share a Provider Across Isolated Components?

I'm working on a framework that allows developers to create extensions for a main app. Extensions can add components to different parts of the app layout, such as the sidebar or workspace, independently of one another. Here's an example of the component tree:

<app>
    <Provider key="instance from Extension 1">
        <Provider key="instance from Extension 2">
            <Layout>
                <Sidebar>
                    <Extension1Component1 />
                    <Extension2Component1 />
                </Sidebar>
                <Workspace>
                    <Extension1Component2 />
                    <Extension2Component2 />
                </Workspace>
            </Layout>
        </Provider>
    </Provider>
</app>

Problem:

Each extension should manage its own state and logic independently. Components from the same extension (Extension1Component1, Extension1Component2, etc.) need to share a context provider instance without interference from other extensions' providers.

If the logic were entirely under our control, solutions like Zustand would work perfectly to maintain a shared state. However, problems arise when an extension requires using a third-party library that mandates wrapping components with a provider (e.g., libraries like react-flow). These providers usually need to be placed around the lowest common ancestor of all components requiring shared context.

Goals:

Additional Question:

Would it be possible to restructure the component tree to something like this, ensuring the same Provider instance is shared between scattered components from the same extension?

<app>
    <Layout>
        <Sidebar>
            <Provider key="instance from Extension 1"> 
                {/* Instance is the same as the one below */}
                <Extension1Component1 />
            </Provider>
            <Provider key="instance from Extension 2"> 
                {/* Instance is the same as the one below */}
                <Extension2Component1 />
            </Provider>
        </Sidebar>
        <Workspace>
            <Provider key="instance from Extension 1"> 
                {/* Instance is the same as the one above */}
                <Extension1Component2 />
            </Provider>
            <Provider key="instance from Extension 2"> 
                {/* Instance is the same as the one above */}
                <Extension2Component2 />
            </Provider>
        </Workspace>
    </Layout>
</app>

This would enable wrapping individual components in their respective providers, but the instances must remain consistent across different parts of the app for each extension. If this approach is feasible, what would be the best way to implement it?

Any suggestions or ideas for tackling this issue would be greatly appreciated!

Upvotes: 1

Views: 39

Answers (0)

Related Questions