Where to put Context Provider in Gatsby?

You define a root layout. In contrast to the normal layout there are no "visible" page elements defined but hidden stuff you need on every page like ContextProviders, React Helmet, themes, etc:

RootLayout.jsx:

export default function RootLayout({ children }) {
  return (
    <>
      <Helmet />
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <ContextProvider>
            {children}
          </ContextProvider>
        </ThemeProvider>
    </>
  );
}

Gatsby calls this root layout implicitly via gatsby-browser.js and gatsby-ssr.js and applies it to each of your pages. Those two identical lines of code are all you need for Gatsby to handle the rest for you.

gatsby-browser.js:

export const wrapRootElement = ({ element }) => <RootLayout>{element}</RootLayout>;

gatsby-ssr.js:

export const wrapRootElement = ({ element }) => <RootLayout>{element}</RootLayout>;

Summary:

  • You put your Context Provider in a root layout.

References:

  • I asked related questions here and here. The code I provided in this answer is the solution to your and my question. It is good coding practice adapted from frameworks such as React Redux to wrap your whole app with the Context Provider if your whole app needs this information.
  • The blog post @Lionel T mentioned.