The provider's value is a new object on every render. Does a memoized reader render again?
App provides { theme, setTheme } and also keeps a like count. Logo and ThemeLabel are both wrapped in memo, and only ThemeLabel reads the context. Each component logs when it renders.
import { createContext, memo, useContext, useState } from "react";
const ThemeContext = createContext(null);
const Logo = memo(function Logo() {
console.log("Logo renders");
return <p>Tea shop</p>;
});
const ThemeLabel = memo(function ThemeLabel() {
const { theme } = useContext(ThemeContext);
console.log("ThemeLabel renders");
return <p>Theme: {theme}</p>;
});
export default function App() {
const [theme, setTheme] = useState("light");
const [likes, setLikes] = useState(0);
console.log("App renders");
return (
<ThemeContext value={{ theme, setTheme }}>
<Logo />
<ThemeLabel />
<button onClick={() => setLikes(likes + 1)}>Like ({likes})</button>
</ThemeContext>
);
}
It runs in development, rendered as <App />, and then:
- You click Like (0) once.
Practice it in the editor, with tests
The answer
Work out every line it logs, in order, and what the page shows at the end. Then check.
Checking your sign-in…