Performance: Avoiding prop drilling
This affects interaction responsiveness and rendering speed by reducing unnecessary component re-renders and deep prop passing.
const CountContext = React.createContext(); function Parent() { const [count, setCount] = React.useState(0); return ( <CountContext.Provider value={{ count, setCount }}> <Child1 /> </CountContext.Provider> ); } function Child1() { return <Child2 />; } function Child2() { return <Child3 />; } function Child3() { const { count, setCount } = React.useContext(CountContext); return <button onClick={() => setCount(count + 1)}>{count}</button>; }
function Parent() { const [count, setCount] = React.useState(0); return <Child1 count={count} setCount={setCount} />; } function Child1({ count, setCount }) { return <Child2 count={count} setCount={setCount} />; } function Child2({ count, setCount }) { return <Child3 count={count} setCount={setCount} />; } function Child3({ count, setCount }) { return <button onClick={() => setCount(count + 1)}>{count}</button>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Prop drilling through many components | No extra DOM nodes | Multiple re-renders of intermediate components | Increased paint due to re-renders | [X] Bad |
| Using React Context to share data | No extra DOM nodes | Re-renders only consuming components | Reduced paint cost | [OK] Good |
prop drilling causes in React applications?createContext to create a context object for sharing data.const MyContext = React.createContext();. The other options are hooks used for different purposes.Child component?const MyContext = React.createContext('default');
function Parent() {
return (
);
}
function Child() {
const value = React.useContext(MyContext);
return <div>{value}</div>;
}Parent component provides the value 'hello' via MyContext.Provider.Child component uses useContext(MyContext), so it receives the nearest provider's value, which is 'hello'.const MyContext = React.createContext();
function Parent() {
const value = 'data';
return <Child />;
}
function Child() {
const value = React.useContext(MyContext);
return <div>{value}</div>;
}Parent component returns <Child /> without wrapping it in MyContext.Provider.useContext(MyContext) returns the default value, which is undefined here, likely not intended.ThemeContext provides a theme string. You want to avoid prop drilling and also allow components to update the theme. Which approach correctly combines context and state to achieve this?createContext(), then in a top-level component use useState to hold theme and pass both theme and setTheme in the Provider's value.useContext to get both and can read or update the theme without prop drilling.Pass the test and this pattern moves unknown