Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Use the useContext Hook to Consume Context in Function Components


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: 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.

    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.

    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.

    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.

    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.

    Now, when we save, the app is still working, and we've saved four levels of nesting.