React · Lesson 48 of 120
Context with State
A logged-in user.
Context becomes really useful when you combine it with state. Put the state in a parent, and provide both the value and a way to change it.
- Context plus state
- Value and setter
- Anywhere below
Logging in
App keeps the user in state. It provides the user and the setter together, in one object. The header shows the user. The login button, deep in the page, calls set user. We click it. Run it.
App.jsxjsx
import { createContext, useContext, useState } from "react";
const AuthContext = createContext(null);
function Header() {
const { user } = useContext(AuthContext);
return <h2>{user ? `Hello, ${user}` : "Not signed in"}</h2>;
}
function LoginButton() {
const { user, setUser } = useContext(AuthContext);
return user ? null : <button id="login" onClick={() => setUser("Priya")}>Sign in</button>;
}
export default function App() {
const [user, setUser] = useState(null);
return (
<AuthContext value={{ user, setUser }}>
<Header />
<main className="box"><LoginButton /></main>
</AuthContext>
);
}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}Also uses actions.json
[{"click": "#login"}]Summary
Combine context with state to share data, and a way to change it, across the app. Next, use reducer.
Key takeaways- useState in parent
- { user, setUser }
- Anywhere below
Next up: useReducer — actions and a reducer