#Nextjs global context

1 messages · Page 1 of 1 (latest)

stark acornBOT
#

Hi @verbal delta. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

In Next.js 13, context is not supported in Server Components, which includes _document.js. To achieve a global state using React Contexts, you should create your context and render its provider inside of a Client Component. Then, wrap the <Component /> in the _app.js file with your context provider.

Here's an example:

  1. Create a context and its provider in a separate file, e.g., app/theme-provider.tsx:
// app/theme-provider.tsx
'use client';

import { createContext } from 'react';

export const ThemeContext = createContext({});

export default function ThemeProvider({ children }) {
  return (
    <ThemeContext.Provider value="dark">
      {children}
    </ThemeContext.Provider>
  );
}
  1. Wrap the <Component /> in the _app.js file with your ThemeProvider:
// pages/_app.js
import ThemeProvider from '../app/theme-provider';

export default function MyApp({ Component, pageProps }) {
  return (
    <ThemeProvider>
      <Component {...pageProps} />
    </ThemeProvider>
  );
}

By doing this, all other Client Components throughout your app will be able to consume this context.

Source: Server and Client Components - Context (https://beta.nextjs.org/docs/rendering/server-and-client-components#context)

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

An overview of essential React features for building Next.js Applications, including Server Components.