Performance: Consuming context
This affects interaction responsiveness and rendering speed when components read shared data.
Split context into smaller contexts or use memoized selectors to consume only needed parts. const value = useContext(MyContext); const selected = useMemo(() => value.part, [value.part]);
const value = useContext(MyContext); // used in many components deeply nested // context value changes frequently
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Single large context with frequent changes | Many components re-render | Multiple reflows per update | High paint cost | [X] Bad |
| Split context or memoized selectors | Only necessary components re-render | Single or few reflows | Lower paint cost | [OK] Good |
useContext in React?useContextuseContext is a React hook used to access data from a context object inside a component.ThemeContext inside a functional component?useContext is called with the context object as an argument: useContext(ThemeContext).const UserContext = React.createContext('Guest');
function DisplayUser() {
const user = React.useContext(UserContext);
console.log(user);
return <div>Hello, {user}!</div>;
}
function App() {
return (
<UserContext.Provider value="Alice">
<DisplayUser />
</UserContext.Provider>
);
}DisplayUser is inside the Provider, it receives the value "Alice" from context.const LanguageContext = React.createContext('English');
function Greeting() {
const language = useContext(LanguageContext);
return <h1>Hello in {language}</h1>;
}
function App() {
return <Greeting />;
}useContext but does not import or prefix it with React.useContext from React or using React.useContext, this causes a ReferenceError.ThemeContext provides a value at the top level. You want to consume this context in a deeply nested component without passing props through intermediate components. Which approach correctly achieves this?ThemeContext.Provider must wrap the component tree to supply the context value.useContext(ThemeContext) reads the value without needing props passed down.Pass the test and this pattern moves unknown