Created
December 5, 2022 13:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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