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
1×
Become a member
to unlock all features

Level Up!

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

Autoplay

    Use contextType to Consume Context in a React Class Without a Consumer

    Dave CeddiaDave Ceddia
    reactReact
    ^16.6.0

    React 16.6 introduced the ability to consume data from context without using the Consumer component 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 by using the contextType property.

    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    Instructor: 00:00 React 16.6 introduced the ability for class components to access context directly without having to use a consumer and the render props pattern. To do this, at the top of the class, we can declare a static property called contextType and set it equal to the full user context.

    00:16 It needs to be the full context and not just the consumer. Right now, user context is only exporting provider and consumer. We'll go into that file. At the top, we'll create a variable called user context and save the context into there as well as destructuring provider and consumer.

    00:33 Then at the bottom, we can export this user context. Back in user menu, we can import the user context which we're already using. Down in the render function, we don't need to use the consumer anymore, because we can access these values directly.

    00:48 This.context is the value that was given to the provider, so we can destructure this directly into user and logout. Now, we can delete the consumer, and we've reduced the nesting by two levels and the app is still working.

    01:01 For a component that uses two contexts, like message list here with user consumer and email consumer, it's important to know that this contextType property is only available on classes.

    01:11 For a component like message list, we would have to convert this to a class before we could set the contextType and contextType only works for a single context. If it's using two contexts like this, we'd only be able to save one of them into contextType.

    Discuss

    Discuss