Home > front end >  Order of React Context Providers
Order of React Context Providers

Time:10-31

If I have multiple context providers, does the order matter? It does seem like it does, but I can't find any official documentation on it.

For instance:

<SessionProvider>
  <AuthProvider>
    <App />
  </AuthProvider>
</SessionProvider>

The above seems to execute the useEffect code within the AuthProvider before it executes it within SessionProvider (both of which are utilizing React context).

Thanks for the help!

CodePudding user response:

Actually if you're not using session context inside of auth context or there isn't any nested context used, it doesn't matter.

But if you're using some data originated from SessionProvider inside of AuthProvider, of course The Session context data must be available in AuthProvider, hence the Session must be used as the top parent element.

CodePudding user response:

Most of the time the order matter, But that's just the framework trying to render components inside out, so that when you try to access a sub-component, it will be there.

  • Related