How to useContext in React?

omkarscode

Omkar Bhagat

Posted on October 6, 2021

How to useContext in React?

In this post I'll quickly explain why and how to useContext in React. First let's look at the why!

Let's say we want to pass a value from the root component to a nested component 3 levels down in the following structure:

App
  - Child
    - ChildChild
      - ChildChildChild
Enter fullscreen mode Exit fullscreen mode

We know it can be done using props as follows:

function App() {
  const myColor = 'blue'
  return (
    <>
      <Child color={myColor}/>
    </>
  )
}

function Child(props) {
  return (
    <>
      <ChildChild color={props.color} />
    </>
  )
}

function ChildChild(props) {
  return (
    <>
      <ChildChildChild color={props.color} />
    </>
  )
}

function ChildChildChild(props) {
  return (
    <>
      {props.color}
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

But what if we could skip the first and the second child and go straight to the third child? We could do that with useContext as follows:

const AppContext = React.createContext()

function App() {
  const color = 'blue'
  return (
    <>
      <AppContext.Provider value={color}>
        <Child/>
      </AppContext.Provider>
    </>
  );
}

function Child() {
  return (
    <>
      <ChildChild/>
    </>
  )
}

function ChildChild() {
    return (
      <>
        <ChildChildChild/>
      </>
    )
  }

function ChildChildChild() {
  const newcolor = React.useContext(AppContext)
  return (
    <>
      {newcolor}
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Isn't this much cleaner? We start to see its utility once we separate the components into their individual files.

As mentioned in the React docs, a component calling useContext will always re-render when the context value changes.

Here's a quick example of that:

const AppContext = React.createContext()

function App() {
  const [color, setColor] = React.useState('blue')
  setTimeout(() => {
    setColor('green')
  }, 2000);

  return (
    <>
      <AppContext.Provider value={color}>
        <Child />
      </AppContext.Provider>
    </>
  );
}

function Child() {
  return (
    <>
      <ChildChild />
    </>
  )
}

function ChildChild() {
  return (
    <>
      <ChildChildChild />
    </>
  )
}

function ChildChildChild() {
  const newcolor = React.useContext(AppContext)
  return (
    <>
      {newcolor}
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

When we use color as a state and then update the state after 2 seconds, the ChildChildChild component re-renders to say green.

I hope this helps to make useContext a bit easy to grasp for anyone learning React.

💖 💪 🙅 🚩
omkarscode
Omkar Bhagat

Posted on October 6, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related