Created
March 14, 2024 18:43
-
-
Save jackbonaguro/54d0fdd93cdbc7814e12c5661929c454 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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