Introduction
Why Context API?
Basic Setup of Context API
1 . Create the Context
2 . Provide Context in Layout (Works on Server)
3 . Consume Context in Server or Client Components
4 . Client Component Fallback
Benefits for SSR
Final Thoughts
When building scalable React applications, especially with Server Components, it's essential to manage state in a way that is both efficient and sharable across multiple layers. That’s where the React Context API comes in.
This blog explores how to set up and use the Context API in modern React projects, with examples that work seamlessly in React Server Components environments like Next.js 13+.
The Context API lets you share global data like authentication, themes, user preferences, and language settings across the app without manually passing props.
It’s lighter than Redux and ideal for simple to moderate state-sharing scenarios, perfect for modern server-rendered apps.
// context/ThemeContext.tsx
import { createContext, useContext } from "react";
export const ThemeContext = createContext({ theme: "light" });
// app/layout.tsx (in Next.js 13+ App Router)
import { ThemeContext } from "@/context/ThemeContext";
export default function RootLayout({ children }) {
const themeValue = { theme: "dark" };
return (
<html>
<body>
<ThemeContext.Provider value={themeValue}>
{children}
</ThemeContext.Provider>
</body>
</html>
);
}
Server Component :
// app/page.tsx
import { ThemeContext } from "@/context/ThemeContext";
import { useContext } from "react";
export default function Page() {
const { theme } = useContext(ThemeContext);
return <div>Current theme is: {theme}</div>;
}
If you hit hydration issues or dynamic interactions, wrap your consumer in "use client" directive:
"use client";
import { useContext } from "react";
import { ThemeContext } from "@/context/ThemeContext";
export function ThemeLabel() {
const { theme } = useContext(ThemeContext);
return <span>{theme}</span>;
}
React’s Context API is an elegant tool for managing state, especially in applications using SSR or server components. By understanding how to structure providers and consumers, you can eliminate complexity while maintaining clean, reusable code.
Software Engineer
Senior Software Engineer