main
ts 40 lines 1.09 KB
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8 import React from 'react';
9
10 /**
11 * Replacement to React.createContext.
12 *
13 * Does not take any default value and avoids non-null assertions when using
14 * the value of the context, like the following scenario.
15 *
16 * ```ts
17 * const StoreDispatchContext = useContext<Dispatch<ReducerAction>>(null);
18 * const dispatchStore = useContext(StoreDispatchContext);
19 * ...
20 * dipatchStore!({ ... });
21 * ```
22 *
23 * Instead, it throws an error when `useContext` is not called within a
24 * Provider with a value.
25 */
26 export default function createContext<T>(): {
27 useContext: () => NonNullable<T>;
28 Provider: React.Provider<T | null>;
29 } {
30 const context = React.createContext<T | null>(null);
31
32 function useContext(): NonNullable<T> {
33 const c = React.useContext(context);
34 if (!c)
35 throw new Error('useContext must be within a Provider with a value');
36 return c;
37 }
38
39 return {useContext, Provider: context.Provider};
40 }