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 a React Context Consumer Outside of the Matching Provider

    Dave CeddiaDave Ceddia

    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.



    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




    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.