0
0
Reactframework~3 mins

Creating context in React - Why You Should Know This

Choose your learning style9 modes available
The Big Idea

Discover how to share data effortlessly across your React app without endless prop passing!

The Scenario

Imagine you have a React app with many components, and you want to share user settings like theme or language across them all.

You try passing these settings down through every component as props.

The Problem

Passing props manually through many layers is tiring and error-prone.

If you add or remove components, you must update all those props everywhere.

This makes your code messy and hard to maintain.

The Solution

Creating context lets you share data globally in your React app without passing props manually.

Any component can access the shared data directly, making your code cleaner and easier to update.

Before vs After
Before
function App() {
  return <Parent user={user} />;
}
function Parent({ user }) {
  return <Child user={user} />;
}
function Child({ user }) {
  return <Display user={user} />;
}
After
const UserContext = React.createContext();
function App() {
  return <UserContext.Provider value={user}>
    <Child />
  </UserContext.Provider>;
}
function Child() {
  const user = React.useContext(UserContext);
  return <Display user={user} />;
}
What It Enables

It enables easy sharing of data across many components without messy prop passing.

Real Life Example

Think of a website where the user chooses a dark or light theme once, and every part of the site updates automatically without extra code.

Key Takeaways

Passing props through many components is hard and messy.

Creating context shares data globally in React apps.

It makes your code cleaner and easier to maintain.