React › Context API
How would you build a custom hook to make using a specific Context simpler and safer?
IntermediateAnswer
You can write a small custom hook that calls useContext internally and throws a clear, helpful error if it is used outside its matching Provider. This saves other developers from having to import both useContext and the context itself every time, and catches mistakes early with a clear message.
function useUser() {
const context = useContext(UserContext);
if (context === undefined) {
throw new Error('useUser must be used inside a UserProvider');
}
return context;
}
// Usage elsewhere in the app
const user = useUser();Real-world example A team creates a useAuth custom hook around their authentication context, so any developer who accidentally forgets to wrap a component in the AuthProvider immediately gets a clear, helpful error message instead of a confusing crash.