Skip to content

Instantly share code, notes, and snippets.

@Andarist
Created December 5, 2022 13:22
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Andarist/5b7b2715c640be8cebe3c611225dc0d9 to your computer and use it in GitHub Desktop.
Save Andarist/5b7b2715c640be8cebe3c611225dc0d9 to your computer and use it in GitHub Desktop.
Hide value initialization in a React-oriented helper using context and conditional server/browser values
function createLongLastingContext<T>(factory: () => T) {
const defaultValue = typeof document !== "undefined" ? factory() : null;
const ctx = React.createContext<T | null>(defaultValue);
return {
useContext: () => {
const value = React.useContext(ctx);
if (!value) {
throw new Error("Context not initialized.");
}
return value;
},
Provider: ({ children }) => {
return (
<ctx.Provider
value={typeof document !== "undefined" ? defaultValue : factory()}
>
{children}
</ctx.Provider>
);
},
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment