React: The signed-in user in context

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 UserContext providing { user, login, logout }, where user is a name or null, kept in state in App.
  • Header shows Signed in as NAME and a button Log out when there is a user, and Not signed in otherwise, in a header element. Greeting shows Welcome back, NAME! or Please log in. in a p with the id greeting.
  • LoginForm (shown only when there is no user) has an input with the id name and a submit button Log in; it calls login with 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>
  );
}

Lesson: Context: sharing values across the tree →