· 6 years ago · Aug 29, 2019, 08:00 AM
1// create context with no upfront defaultValue
2// without having to do undefined check all the time
3function createCtx<A>() {
4 const ctx = React.createContext<A | undefined>(undefined)
5 function useCtx() {
6 const c = React.useContext(ctx)
7 if (!c) throw new Error("useCtx must be inside a Provider with a value")
8 return c
9 }
10 return [useCtx, ctx.Provider] as const
11}
12// usage - no need to specify value upfront!
13export const [useCtx, SettingProvider] = createCtx<string>()
14export function App() {
15 // get a value from a hook, must be in a component
16 const key = useLocalStorage('key')
17 return (
18 <SettingProvider value={key}>
19 <Component />
20 </SettingProvider>
21 )
22}
23export function Component() {
24 const key = useCtx() // can still use without null check!
25 return <div>{key}</div>
26}
27
28
29function useLocalStorage(a: string) {
30 return 'secretKey' + a
31}