Share the signed-in user, and the functions that change it, with any component that needs them.
What to build
A small app where a header and a greeting both follow the signed-in user.
Requirements
- Create
UserContextproviding{ user, login, logout }, whereuseris a name or null, kept in state inApp. HeadershowsSigned in as NAMEand abuttonLog outwhen there is a user, andNot signed inotherwise, in aheaderelement.GreetingshowsWelcome back, NAME!orPlease log in.in apwith the idgreeting.LoginForm(shown only when there is no user) has aninputwith the idnameand a submitbuttonLog in; it callsloginwith the trimmed name, if not empty.
Constraints
No component receives the user as a prop.
Example
Logging in as Ada shows "Signed in as Ada" in the header and "Welcome back, Ada!"; Log out goes back to "Not signed in".
Why it works
The provider gives every component the same user and the same functions to change it, so the header, the greeting and the form stay in step without props threaded through the tree.
Hints
Hint 1
Provide an object: { user, login, logout }, with user kept in App's state.
Hint 2
Header and Greeting both call useContext; neither gets the user as a prop.
Solution
Show one correct solution (try it yourself first)
import { createContext, useContext, useState } from "react";
const UserContext = createContext({ user: null, login: () => {}, logout: () => {} });
function Header() {
const { user, logout } = useContext(UserContext);
return (
<header>
{user ? (
<>
Signed in as {user} <button onClick={logout}>Log out</button>
</>
) : (
"Not signed in"
)}
</header>
);
}
function Greeting() {
const { user } = useContext(UserContext);
return <p id="greeting">{user ? "Welcome back, " + user + "!" : "Please log in."}</p>;
}
function LoginForm() {
const { login } = useContext(UserContext);
const [name, setName] = useState("");
function handleSubmit(event) {
event.preventDefault();
if (name.trim()) login(name.trim());
}
return (
<form onSubmit={handleSubmit}>
<input id="name" value={name} onChange={(e) => setName(e.target.value)} />
<button type="submit">Log in</button>
</form>
);
}
export default function App() {
const [user, setUser] = useState(null);
const value = { user, login: setUser, logout: () => setUser(null) };
return (
<UserContext value={value}>
<Header />
<Greeting />
{!user && <LoginForm />}
</UserContext>
);
}