rallly/components/use-required-context.ts
2022-05-09 08:21:53 +01:00

14 lines
348 B
TypeScript

import React from "react";
export const useRequiredContext = <T>(
context: React.Context<T | null>,
errorMessage?: string,
) => {
const contextValue = React.useContext(context);
if (contextValue === null) {
throw new Error(
errorMessage ?? `Missing context provider: ${context.displayName}`,
);
}
return contextValue;
};