🎁

12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
13 : 08 : 46 : 56
Join egghead, unlock knowledge.

Want more egghead? It's 58% off for a limited time only!

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

Unlock All Content for 40% Off
1×
Become a member
to unlock all features
Autoplay

    Use a React Context Consumer Outside of the Matching Provider

    Dave CeddiaDave Ceddia
    reactReact
    ^16.6.0

    You may come upon a case where you have a generic component that can consume a Context, but doesn’t require that Context in order to work. On the flip side, you may want to validate that a component is always used inside a required parent Context. In this lesson we’ll see how to set a default value on a Provider and access that default in the Consumer, as well as how to validate that a Consumer is used correctly, by checking the value it receives and throwing an error if it is missing.

    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
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: In this app, we've created a context to pass around a color. The fancy button component consumes that color, and uses that color as the class name. Then down in the app component, we can see we're rendering the fancy button once outside of any context, and then three more times. One's red, one's green, and one's blue.

    If we look over to the elements inspector, you can see that these three have a red, green, and blue class, but this top one has undefined as a class. That's because when this context was created, it wasn't given a default value. The default is undefined.

    Still, though, even though there's no value provided, the consumer can render out successfully, and the color just ends up undefined. We can provide a default value at creation time. From then on, if a consumer is used outside the matching provider, it'll receive this default.

    You might have a different situation, where it doesn't make sense to ever use a consumer outside of its matching provider. In this case, you can leave the default as undefined. Then inside the consumer, we can change this function to return the component.

    Before we return, we can check if the type of the color is undefined. If so, throw an error that this component must be used inside a matching provider. Now, if we save this, we get an error. We can go and fix our code by either removing the button or moving it inside a provider.