Skip to content

Instantly share code, notes, and snippets.

@brunoh3art
Created February 27, 2024 15:29
Show Gist options
  • Select an option

  • Save brunoh3art/b2269c70d57a0557e278872471cebc9c to your computer and use it in GitHub Desktop.

Select an option

Save brunoh3art/b2269c70d57a0557e278872471cebc9c to your computer and use it in GitHub Desktop.
create Safe Context
import React, { createContext, useContext } from "react";
export function createSafeContext<ContextValue>(errorMessage: string) {
const Context = createContext<ContextValue | null>(null);
const useSafeContext = () => {
const ctx = useContext(Context);
if (ctx === null) {
throw new Error(errorMessage);
}
return ctx;
};
const Provider = ({ children, value }: { value: ContextValue; children: React.ReactNode }) => (
<Context.Provider value={value}>{children}</Context.Provider>
);
return [Provider, useSafeContext] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment