Use the useContext Hook to Consume Context in Function Components

Share this video with your friends

Send Tweet

React Hooks introduced a number of useful functions, one of which is useContext. It allows you to consume a Context in a function component without using a Consumer directly. This helps to cut down on unnecessary nesting in your components’ JSX, making them easier to read. In this lesson we’ll see how to replace a Consumer with the useContext hook.

ed leach
ed leach
~ 6 years ago

In index.js what is the purpose of const s = useState(7) on line 10? I see that it is logged out on the next line, but I still don't know why it is there.

Dave Ceddia
Dave Ceddia(instructor)
~ 6 years ago

That is ... I'm not sure why that's there 😄 I think I was testing whether I had the right version of React installed and forgot to remove it. You can safely ignore those lines 👍

Dave Ceddia
Dave Ceddia(instructor)
~ 6 years ago

FYI: The 'before' code for this lesson is here if you need it.

Conrado Fonseca
Conrado Fonseca
~ 6 years ago

When using the useContext, do I need to have the context provider wrapper (eg. in the index.js page)?

Dave Ceddia
Dave Ceddia(instructor)
~ 6 years ago

@Conrado: Yeah, useContext takes the place of the Consumer, but you still need a Provider somewhere higher up in the tree.

Nazariy
Nazariy
~ 5 years ago

So it is possible to have two (or more) contexts with hooks, but what about having multiple contexts in a class component? Are we restricted to just one context (via contextType)?

Dave Ceddia
Dave Ceddia(instructor)
~ 5 years ago

@Nazariy Yep, you can grab values from multiple contexts by calling useContext as many times as you want. With a class you can use multiple contexts by nesting the Consumer elements, but you can only assign a single one to contextType.