Skip to content

Instantly share code, notes, and snippets.

@jackbonaguro
Created March 14, 2024 18:43
Show Gist options
  • Save jackbonaguro/54d0fdd93cdbc7814e12c5661929c454 to your computer and use it in GitHub Desktop.
Save jackbonaguro/54d0fdd93cdbc7814e12c5661929c454 to your computer and use it in GitHub Desktop.
import React, { createContext, useContext } from 'react';
type HelloWorldContextType = {
hello: string;
};
// create context with no default values
export const HelloWorldContext = createContext<HelloWorldContextType | undefined>(undefined);
export const WorkspaceProvider = ({ children }: { children: React.ReactElement }) => {
// async or optional operation here
const value: HelloWorldContextType | undefined = {
hello: 'world',
};
// early return with undefined value
if (typeof value === 'undefined') {
// should include additional logic to resolve the issue, like logging user out
return <></>;
}
// render children with guaranteed value
return <HelloWorldContext.Provider value={value}>{children}</HelloWorldContext.Provider>;
};
export const useHelloWorld = () => {
// infer context is not undefined, as no uses of the hook will be rendered in that case
return useContext(HelloWorldContext) as HelloWorldContextType;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment