0
0
NextJSframework~3 mins

Why React context in client components in NextJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how React context saves you from endless data passing headaches!

The Scenario

Imagine you have a website where many parts need to know the user's theme preference, like dark or light mode. Without React context, you must pass this theme information through every component manually, like passing a note down a long line of friends.

The Problem

Passing data manually through many components is tiring and error-prone. If you forget to pass the theme somewhere, that part won't update correctly. It also makes your code messy and hard to change later.

The Solution

React context lets you share data like the theme directly to any component that needs it, without passing it through every step. This keeps your code clean and makes updates easy and reliable.

Before vs After
Before
function App() {
  return <Page theme="dark" />;
}
function Page({ theme }) {
  return <Content theme={theme} />;
}
function Content({ theme }) {
  return <div>{theme}</div>;
}
After
import React from 'react';
const ThemeContext = React.createContext('light');
function App() {
  return <ThemeContext.Provider value="dark">
    <Page />
  </ThemeContext.Provider>;
}
function Page() {
  return <Content />;
}
function Content() {
  const theme = React.useContext(ThemeContext);
  return <div>{theme}</div>;
}
What It Enables

It enables easy sharing of data across many components without messy manual passing, making your app more flexible and easier to maintain.

Real Life Example

Think of a music app where the user's language preference is needed in many places. React context lets you set the language once and all parts of the app automatically use it.

Key Takeaways

Passing data manually through many components is hard and error-prone.

React context shares data directly to any component that needs it.

This makes your code cleaner, easier to update, and more reliable.