Liam Hales
Senior Software Engineer
TypeScript
React
November 2021 - 3 years ago
React
defaultValue
createContext
Provider
defaultValue
Provider
undefined
Provider
undefined
useContext
defaultValue
undefined
createContext
const context = createContext<IContext | undefined>(undefined);
useContext
undefined
Provider
const useCustomContext<T extends Record<string, unknown>>(
context: Context<T | undefined>
): T {
// Get the context value which could be undefined
const value = useContext(context);
// Check the value is not undefined and
// has been initialised by the provider
if (value == null) {
throw new Error(
'The "useContext" hook must be used within the corresponding context "Provider"'
);
}
return value;
}
throw
Error
Provider
const { value ... } = useCustomContext(context);
React
undefined
Error