cf.completefrontend

Predict the outputHard

Which components render again when the theme provider's state changes?

ThemeProvider keeps the theme in state. App passes it Sidebar as children, and ThemeProvider renders a memo Toolbar and a Footer itself. Every component logs when it renders.

What does it log, and what does the page show?
import { createContext, memo, useContext, useState } from "react";
 
const ThemeContext = createContext("light");
 
function ThemeProvider({ children }) {
  const [theme, setTheme] = useState("light");
  console.log("ThemeProvider");
  return (
    <ThemeContext value={theme}>
      <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>Switch theme</button>
      <Toolbar />
      {children}
      <Footer />
    </ThemeContext>
  );
}
 
const Toolbar = memo(function Toolbar() {
  console.log("Toolbar");
  return <ThemedButton />;
});
 
function ThemedButton() {
  const theme = useContext(ThemeContext);
  console.log("ThemedButton", theme);
  return <p>Button: {theme}</p>;
}
 
function Sidebar() {
  console.log("Sidebar");
  return (
    <>
      <Label />
      <ThemeBadge />
    </>
  );
}
 
function Label() {
  console.log("Label");
  return <p>Label</p>;
}
 
function ThemeBadge() {
  const theme = useContext(ThemeContext);
  console.log("ThemeBadge", theme);
  return <p>Badge: {theme}</p>;
}
 
function Footer() {
  console.log("Footer");
  return <p>Footer</p>;
}
 
export default function App() {
  console.log("App");
  return (
    <ThemeProvider>
      <Sidebar />
    </ThemeProvider>
  );
}

It runs in development, rendered as <App />, and then:

  1. You click Switch theme once.

The answer

Work out every line it logs, in order, and what the page shows at the end. Then check.

Checking your sign-in…