Course lesson

Validate use of Context using a custom hook and the useContext React hook

What happens if the user of a component that uses the Context api and the useContext hook to define its compound components, renders one of its components outside of the context provider? If this happened, an error would be thrown since the component will not...

Duration
2 min
Access
Free
Transcript
Available

What happens if the user of a component that uses the Context api and the useContext hook to define its compound components, renders one of its components outside of the context provider? If this happened, an error would be thrown since the component will not be able to access the values of the context provided by the parent component.

There are two options to solve this problem, one is to use default values and the other is to create a validation strategy. We can use a custom hook to encapsulate the necessary logic to retrieve and validate the context values and share it between the different compound components.