React Dojo

Search

Search concepts, exercises and quizzes

practiceintermediate

Context without spurious re-renders

Create a ThemeProvider that exposes theme and setTheme. The challenge: if you pass { theme, setTheme } as inline value, every render creates a new object and ALL consumers re-render — even those that don't read theme. Memoize the value.


Objectives

  1. 1.Define ThemeContext with createContext
  2. 2.ThemeProvider stores theme in useState
  3. 3.The value passed to Provider is memoized with useMemo
  4. 4.A useTheme() hook that reads the context and throws an error if there's no Provider
  5. 5.A <Toolbar/> component that reads setTheme — must NOT re-render when the parent tick changes
  6. 6.A memoized <Card/> component that reads theme
your code
Hint

memo + useMemo work together here: Toolbar wrapped in memo only avoids renders if its props (the ctx value via useTheme) are stable. If the value changes by reference, memo is useless.

Related concepts

Was this helpful?
Sign in to give feedback