RecipesChapter 10: TypeScript and React

Providing Types for the Context API

Recipe 10.4 from The TypeScript Cookbook

function App() {
  return (
    <AppContextProvider
      value={{ lang: "en", theme: "dark", authenticated: true }}
    >
      <Header />
    </AppContextProvider>
  );
}

function Header() {
  // consuming Context doesn't change much
  const { authenticated } = useAppContext();
  if (authenticated) {
    return <h1>Logged in!</h1>;
  }
  return <h1>You need to sign in</h1>;
}
Open in TypeScript Playground →