useContext 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>;
}

Complex problems, Simple Solutions