How to replace old React contextTypes with new React context api when using dynamic context data?

Viewed 1022

I have an app which renders multiple roots on a html page. Each root renders a different(or potentially the same) page or component on the website. The app contains a redux store, Since each root shares the same app. To avoid conflicts, a redux store is generated for each root.

Now the redux store has lazy load reducers. Reducers are added as code splitting components get loaded.

To accommodate for this, a function is added to the store to call replaceReducerfrom redux.

So the issue comes when a component is loaded and needs to load a reducer also. The component needs access to the root store from redux provider.

This was achieved using contextTypes in the old react context api to access the store. contextTypes in a wrapper component pulls the current root instance of the store.

But using the new react context api, this does not seem to be compatible. The recommendation was to create a context file and use it in any child components. Doing this, i will need to put the store into the react context provider value. But doing this means that the react context will hold only 1 instance of the store.

How is it possible to make it work just like the old react contextTypes to access the root level provider context accordingly ?

2 Answers

I think there's a misunderstanding here.

Essentially what you want is to read a legacy context (which is what React Redux currently provides, and what you were reading with contextTypes) using the new context API. This won't work. Legacy and new context APIs are completely unrelated (even though they serve the same use case).

When in the future React Redux switches to the new context API you should be able to do that. Note that in either case, using legacy context API with React Redux directly is discouraged, and you should probably use connect() instead.

Maybe this article will help you with the migration to the new context API. Long story short: you could pass the data using the legacy API and read it with the new one. I wouldn't recommend doing this in your particular case though.

Related