The following code has a performance bug that causes `ThemeComponent` to re-render unnecessarily. What is the cause of this bug?

React JS interview question for Advanced practice.

Answer

A new object { theme, toggleTheme } is created for the value prop on every render, causing all consumers to re-render.

Explanation

The performance bug is that a new object is created for the value prop on every render of ThemeProvider. When the provider's parent re-renders, ThemeProvider also re-renders, creating a new value object. Because the object reference is new, React assumes the context has changed and forces a re-render of all consuming components. The fix is to memoize the value with useMemo and the function with useCallback.

Related Questions