| 1 |
import { createContext, useContext } from 'react' |
| 2 |
import type { Context } from 'react' |
| 3 |
|
| 4 |
export const createContextHook = <T>(name: string): [ |
| 5 |
Context<T | undefined>, |
| 6 |
() => T |
| 7 |
] => { |
| 8 |
const contextValue = createContext<T | undefined>(undefined) |
| 9 |
|
| 10 |
const useContextHook = (): T => { |
| 11 |
const value = useContext(contextValue) |
| 12 |
|
| 13 |
if (value === undefined) { |
| 14 |
throw Error(`use${name} can only be used within a ${name} context provider.`) |
| 15 |
} |
| 16 |
|
| 17 |
return value |
| 18 |
} |
| 19 |
|
| 20 |
return [contextValue, useContextHook] |
| 21 |
} |
| 22 |
|