Use a React Context Consumer Outside of the Matching Provider

Dave Ceddia
InstructorDave Ceddia

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

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.

Instructor: [00:00] 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.

[00:19] 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.

[00:35] 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.

[00:51] 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.

[01:04] 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.

Steve
Steve
~ 3 years ago

The code here, like in the first lesson, is the completed version rather than the start code.

Dave Ceddia
Dave Ceddiainstructor
~ 3 years ago

The 'before' code for this lesson can be found here.