How can I use context providers with Nextjs 13 App Router?

1.4k views Asked by At

I have an application created using next 13. In page.js I have all of my context providers wrapping a component that does the route handling for me. Example below

export default function MyApp( {

<someProvider>
  <Content />
</someProvider>

}

const Content = () => {

useEffect(() => {
if (conditional) {
  router.push("some-route")
} else {
  router.push("some-other-route")
}

Both routes which are set up using the new app router conventions wherein the file names are the expected route, and a page.js folder inside holds the component logic. The context from my providers are not being passed when the relevant pages are being routed to based on the conditions I have set. I need the context to be passed, so I'm unsure how to get around this.

I have tried refactoring to use the old next js pages directory conventions, to no avail.

1

There are 1 answers

1
Ashkan Rahnavardi On

You have to wrap {children} with <someProvider> in your layout.tsx file, not your main component in page.tsx

Source: https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns#using-context-providers