Home
Basics
Introduction Setting up environment First Component JSX Component lifecycle Class Based Components Function Based Components Props State Hooks useState hook useEffect hook Events Server requests CSS in React Router third party JavaScriptAdvanced
useContext hook useRef hook useReducer hook Memo useCallback hook Custom Hooks React and ReduxMiscellaneous
React Third Party Components Html templates in React React Interview QnAuseContext hook in react
Let us say there is component X which is nested deep inside other components. If you want to pass the props from top component to component X, you will need to pass props through all components between top component and component X. This is called as prop drilling.
So the problem here is that even though intermediate components do not need the props, they are still being passed to them. To avoid this problem, we use useContext hook.
With useContext hook, we wrap the top component with context provider and then we use useContext hook in the component where we need to access the props.Example
In below example, we have created a context in App and then wrapped component C1 with context provider. All children context provider will be able to access the conext value using useContext hook. C2 is child of C1 hence C2 can access the context value.
import { useState, createContext, useContext } from "react";
const countContext = createContext();
export default function App() {
let [count, setCount] = useState(1);
return (
<countContext.Provider value={count}>
<C1 />
</countContext.Provider>
);
}
function C1() {
console.log("rendering C1");
return <C2 />;
}
function C2() {
const count = useContext(countContext);
console.log("rendering C2", count);
return <span> C2</span>;
}
Web development and Automation testing
solutions delivered!!