Imagine you have a React app with many nested components. You want to share a theme color across all of them.
Why is React Context helpful here compared to passing props?
Think about how props must be passed down through each level even if intermediate components don't need the data.
React Context allows sharing data like theme or user info without passing props through every component. This avoids 'prop drilling' and keeps components simpler.
Given a React Context Provider wrapping components, what happens when the Provider's value changes?
const ThemeContext = React.createContext('light'); function App() { const [theme, setTheme] = React.useState('light'); return ( <ThemeContext.Provider value={theme}> <Toolbar /> <button onClick={() => setTheme('dark')}>Dark Mode</button> </ThemeContext.Provider> ); } function Toolbar() { return <ThemedButton />; } function ThemedButton() { const theme = React.useContext(ThemeContext); return <button>{theme}</button>; }
Think about how React updates components that consume context when the Provider's value changes.
When a Context Provider's value changes, React re-renders all components that use that context to reflect the new value.
Which option correctly uses React Context inside a functional component?
const UserContext = React.createContext(null); function Profile() { // Fill in the blank }
Remember the exact React hook name and how to call it.
The correct hook to consume context is React.useContext. It must be called with the context object.
Consider this code:
const CountContext = React.createContext(0);
const Counter = React.memo(function() {
const count = React.useContext(CountContext);
return <div>Count: {count}</div>;
});
function App() {
const [count, setCount] = React.useState(0);
return (
<CountContext.Provider value={count}>
<Counter />
<button onClick={() => setCount(count + 1)}>Increment</button>
</CountContext.Provider>
);
}But when clicking the button, the Counter does not update. Why?
Think about how React.memo affects re-rendering when context changes.
If a component consuming context is wrapped in React.memo without considering context, it may not re-render when context changes. React.memo only shallowly compares props, not context.
In React, under which condition does a Context Provider cause its consumers to re-render?
React compares the value prop by reference to decide if consumers update.
React Context triggers consumer re-render only if the Provider's value prop changes by reference (strict equality). Deep equality is not checked.