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.
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.
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 👍
FYI: The 'before' code for this lesson is here if you need it.
When using the useContext
, do I need to have the context provider wrapper (eg. in the index.js page)?
@Conrado: Yeah, useContext
takes the place of the Consumer
, but you still need a Provider
somewhere higher up in the tree.
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)?
@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.