AI Hints
Home›React Tutorial›Context
React · Lesson 47 of 120

Providing Values

A theme.

⏱ 2 min read▶ Video at 38:24🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

The default value is only a fallback. To give context a real value, wrap part of the tree in a provider. Everything inside reads that value.

  • Default is a fallback
  • Wrap in a provider
  • Everything inside reads it

A theme

The theme context defaults to light. App wraps the first card in a provider with the value dark. That card reads dark. The second card is outside the provider, so it gets the default. Run it.

App.jsxjsx
import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function Card({ title }) {
  const theme = useContext(ThemeContext);
  const style = theme === "dark" ? { background: "#222", color: "#fff" } : {};
  return <div className="box" style={style}>{title}: {theme} theme</div>;
}

export default function App() {
  return (
    <>
      <ThemeContext value="dark"><Card title="Inside" /></ThemeContext>
      <Card title="Outside" />
    </>
  );
}
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}

Provider rules

In React nineteen, you render the context itself as the provider. Older code writes dot provider after it. Components read the nearest provider above them. And when its value changes, they all re-render.

keyvalue
React 19<ThemeContext value>
Older<ThemeContext.Provider>
Readsnearest provider
Value changesre-render

Summary

Wrap a tree in a provider to give context a value. Next, context with state.

Key takeaways
  • <Context value>
  • Nearest wins
  • Default as fallback
Next up: Context with State — a logged-in user