Context in App dir

I just wanted to understand , if I have global context providers that I need to use in all components, would it be possible to still use server components using app dir in Nextjs if I wrap the children in context Example from next documentation: import { ThemeProvider } from 'acme-theme'; export default function RootLayout({ children }) { return ( <html> <body> {/* Error: createContext can't be used in Server Components */} <ThemeProvider>{children}</ThemeProvider> </body> </html> ); }
6 Replies
stanisław
stanisław14mo ago
Context cannot be used in server components, they are not meant to be interactive.
'use client';

import { ThemeProvider } from 'acme-theme';
import { AuthProvider } from 'acme-auth';

export function Providers({ children }) {
return (
<ThemeProvider>
<AuthProvider>{children}</AuthProvider>
</ThemeProvider>
);
}
'use client';

import { ThemeProvider } from 'acme-theme';
import { AuthProvider } from 'acme-auth';

export function Providers({ children }) {
return (
<ThemeProvider>
<AuthProvider>{children}</AuthProvider>
</ThemeProvider>
);
}
Rendering this Providers in root layout will solve your problem. Wrapping Server component with client component doesn't mean it becomes one.
Yuvaraj
Yuvaraj14mo ago
So if I render them in root layout, I can still use server components for all routes right ??
stanisław
stanisław14mo ago
Yes And only create small client components which consume context
Yuvaraj
Yuvaraj14mo ago
Got it , Thank youuu
JulieCezar
JulieCezar13mo ago
This video explains this pretty in-depth https://www.youtube.com/watch?v=OpMAH2hzKi8
Jack Herrington
YouTube
Did NextJS 13 Break State Management?
NextJS 13 changes the state management game. We now have to support two different ways to get state for React Server Components (RSC) and the traditional client components. Code: https://github.com/jherr/nextjs13-state-zustand NextJS Documentation: https://beta.nextjs.org/docs/styling/css-in-js Console Ninja: https://marketplace.visualstudio.co...
Yuvaraj
Yuvaraj13mo ago
Thank you ,will check out this one