React · Lesson 46 of 120
Context
No more prop drilling.
Passing props through many layers gets tiring. Components in the middle pass along data they don't even use. That's called prop drilling. Context lets a parent share a value with everything below it.
- Props through layers
- Prop drilling
- Context
Prop drilling
The app knows the user. But only the avatar, deep inside, needs it. Without context, the page and the header must pass it along, even though they don't use it.
App
Page
Header
Avatar
A first context
Create context makes a context, with a default value. The avatar reads it with use context. No props are passed through the page or the header. Run it.
App.jsxjsx
import { createContext, useContext } from "react";
const UserContext = createContext("Guest");
function Avatar() {
const user = useContext(UserContext);
return <p className="box">Signed in as {user}</p>;
}
function Header() {
return <header><h2>Northwind Bikes</h2><Avatar /></header>;
}
export default function App() {
return <Header />;
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Summary
Context shares a value with every component below, without prop drilling. Next, providing values.
Key takeaways- createContext
- useContext
- No drilling
Next up: Providing Values — a theme