Use the useContext Hook to Consume Context in Function Components

Dave Ceddia
InstructorDave Ceddia
Share this video with your friends

Social Share Links

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.

Instructor: [00:00] React hooks allow us to access context from a function component without using consumer and without using the render props pattern, saving us a lot of nesting. To do this, we can import useContext from React and we'll change our function body into one that has braces and a return.

[00:15] At the top of the function, we can call useContext with a full context object. That will be user context, which we don't have here yet. This will return the value that was passed into the provider. From there, we can destructure the user from it.

[00:29] We can do the same with the email context, calling useContext and passing in the full email context. Before we can use these, we need to import them. Right now, our contexts only export provider and consumer.

[00:44] We'll open these up. At the top, we'll create a variable to hold the full context and save the context into it, along with destructuring the provider and consumer. At the bottom, we can export user context.

[00:56] We'll go back to message list and do the same for email context, creating the email context variable, saving the context into it, and exporting it. Now, in message list, we can replace the consumers with the full contexts and remove the consumers from the rendered output.

[01:16] Now, when we save, the app is still working, and we've saved four levels of nesting.