@aweebit/react-essentials 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +656 -110
- package/dist/hooks/useEventListener.d.ts +32 -37
- package/dist/hooks/useEventListener.d.ts.map +1 -1
- package/dist/hooks/useEventListener.js +41 -9
- package/dist/hooks/useEventListener.js.map +1 -1
- package/dist/hooks/useForceUpdate.d.ts +49 -0
- package/dist/hooks/useForceUpdate.d.ts.map +1 -1
- package/dist/hooks/useForceUpdate.js +54 -5
- package/dist/hooks/useForceUpdate.js.map +1 -1
- package/dist/hooks/useReducerWithDeps.d.ts +4 -1
- package/dist/hooks/useReducerWithDeps.d.ts.map +1 -1
- package/dist/hooks/useReducerWithDeps.js +4 -1
- package/dist/hooks/useReducerWithDeps.js.map +1 -1
- package/dist/hooks/useStateWithDeps.d.ts +35 -0
- package/dist/hooks/useStateWithDeps.d.ts.map +1 -1
- package/dist/hooks/useStateWithDeps.js +39 -6
- package/dist/hooks/useStateWithDeps.js.map +1 -1
- package/dist/misc/createSafeContext.d.ts +40 -7
- package/dist/misc/createSafeContext.d.ts.map +1 -1
- package/dist/misc/createSafeContext.js +38 -7
- package/dist/misc/createSafeContext.js.map +1 -1
- package/package.json +1 -1
- package/src/hooks/useEventListener.ts +97 -66
- package/src/hooks/useForceUpdate.ts +54 -5
- package/src/hooks/useReducerWithDeps.ts +4 -1
- package/src/hooks/useStateWithDeps.ts +39 -6
- package/src/misc/createSafeContext.ts +40 -7
|
@@ -5,24 +5,55 @@ const moValueSymbol = Symbol('noValue');
|
|
|
5
5
|
* type and a hook that returns the current context value if one was provided,
|
|
6
6
|
* or throws an error otherwise
|
|
7
7
|
*
|
|
8
|
+
* The advantages over vanilla `createContext` are that no default value has to
|
|
9
|
+
* be provided, and that a meaningful context name is displayed in dev tools
|
|
10
|
+
* instead of generic `Context.Provider`.
|
|
11
|
+
*
|
|
8
12
|
* @example
|
|
9
13
|
* ```tsx
|
|
10
|
-
*
|
|
14
|
+
* enum Direction {
|
|
15
|
+
* Up,
|
|
16
|
+
* Down,
|
|
17
|
+
* Left,
|
|
18
|
+
* Right,
|
|
19
|
+
* }
|
|
20
|
+
*
|
|
21
|
+
* // Before
|
|
22
|
+
* const DirectionContext = createContext<Direction | undefined>(undefined);
|
|
23
|
+
* DirectionContext.displayName = 'DirectionContext';
|
|
24
|
+
*
|
|
25
|
+
* const useDirection = () => {
|
|
26
|
+
* const direction = useContext(DirectionContext);
|
|
27
|
+
* if (direction === undefined) {
|
|
28
|
+
* // Called outside of a <DirectionContext.Provider> boundary!
|
|
29
|
+
* // Or maybe undefined was explicitly provided as the context value
|
|
30
|
+
* // (ideally that shouldn't be allowed, but it is because we had to include
|
|
31
|
+
* // undefined in the context type so as to provide a meaningful default)
|
|
32
|
+
* throw new Error('No DirectionContext value was provided');
|
|
33
|
+
* }
|
|
34
|
+
* // Thanks to the undefined check, the type is now narrowed down to Direction
|
|
35
|
+
* return direction;
|
|
36
|
+
* };
|
|
37
|
+
*
|
|
38
|
+
* // After
|
|
39
|
+
* const { DirectionContext, useDirection } =
|
|
40
|
+
* createSafeContext<Direction>()('Direction'); // That's it :)
|
|
11
41
|
*
|
|
12
42
|
* const Parent = () => (
|
|
13
|
-
*
|
|
43
|
+
* // Providing undefined as the value is not allowed 👍
|
|
44
|
+
* <Direction.Provider value={Direction.Up}>
|
|
14
45
|
* <Child />
|
|
15
|
-
* </
|
|
46
|
+
* </Direction.Provider>
|
|
16
47
|
* );
|
|
17
48
|
*
|
|
18
|
-
* const Child = () =>
|
|
49
|
+
* const Child = () => `Current direction: ${Direction[useDirection()]}`;
|
|
19
50
|
* ```
|
|
20
51
|
*
|
|
21
52
|
* @returns
|
|
22
53
|
* A function that accepts a single string argument `displayName` (e.g.
|
|
23
|
-
* `"
|
|
24
|
-
* - ``` `${displayName}Context` ``` (e.g. `
|
|
25
|
-
* - ``` `use${displayName}` ``` (e.g. `
|
|
54
|
+
* `"Direction"`) and returns an object with the following properties:
|
|
55
|
+
* - ``` `${displayName}Context` ``` (e.g. `DirectionContext`): the context
|
|
56
|
+
* - ``` `use${displayName}` ``` (e.g. `useDirection`): a hook that returns the
|
|
26
57
|
* current context value if one was provided, or throws an error otherwise
|
|
27
58
|
*/
|
|
28
59
|
export function createSafeContext() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createSafeContext.js","sourceRoot":"","sources":["../../src/misc/createSafeContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+B,aAAa,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AAG/E,MAAM,aAAa,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"createSafeContext.js","sourceRoot":"","sources":["../../src/misc/createSafeContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+B,aAAa,EAAE,UAAU,EAAE,MAAM,OAAO,CAAC;AAG/E,MAAM,aAAa,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AA6BxC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDG;AACH,MAAM,UAAU,iBAAiB;IAC/B,OAAO,CACL,WAEgD,EACnB,EAAE;QAC/B,MAAM,WAAW,GAAG,GAAG,WAA0B,SAAkB,CAAC;QACpE,MAAM,QAAQ,GAAG,MAAM,WAA0B,EAAW,CAAC;QAE7D,MAAM,OAAO,GAAG,aAAa,CAA2B,aAAa,CAAC,CAAC;QACvE,OAAO,CAAC,WAAW,GAAG,WAAW,CAAC;QAElC,OAAO;YACL,CAAC,WAAW,CAAC,EAAE,OAA+B;YAC9C,CAAC,QAAQ,CAAC,EAAE,GAAG,EAAE;gBACf,MAAM,KAAK,GAAG,UAAU,CAAC,OAAO,CAAC,CAAC;gBAClC,IAAI,KAAK,KAAK,aAAa,EAAE,CAAC;oBAC5B,MAAM,IAAI,KAAK,CAAC,MAAM,WAAW,qBAAqB,CAAC,CAAC;gBAC1D,CAAC;gBACD,OAAO,KAAK,CAAC;YACf,CAAC;SAKF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
|
package/package.json
CHANGED
|
@@ -7,13 +7,26 @@
|
|
|
7
7
|
|
|
8
8
|
import { useEffect, useMemo, useRef } from 'react';
|
|
9
9
|
|
|
10
|
+
type UseEventListenerOverloadArgs<
|
|
11
|
+
EventMap,
|
|
12
|
+
K extends keyof EventMap,
|
|
13
|
+
T extends EventTarget,
|
|
14
|
+
> = [
|
|
15
|
+
target: T | null,
|
|
16
|
+
eventName: K,
|
|
17
|
+
handler: (this: NoInfer<T>, event: EventMap[K]) => void,
|
|
18
|
+
options?: AddEventListenerOptions | boolean,
|
|
19
|
+
];
|
|
20
|
+
|
|
10
21
|
/**
|
|
11
|
-
* Adds `handler` as a listener for the event `eventName` of `
|
|
22
|
+
* Adds `handler` as a listener for the event `eventName` of `target` with the
|
|
12
23
|
* provided `options` applied
|
|
13
24
|
*
|
|
14
|
-
* If `
|
|
25
|
+
* If `target` is not provided, `window` is used instead.
|
|
15
26
|
*
|
|
16
|
-
* If `
|
|
27
|
+
* If `target` is `null`, no event listener is added. This is useful when
|
|
28
|
+
* working with DOM element refs, or when the event listener needs to be removed
|
|
29
|
+
* temporarily.
|
|
17
30
|
*
|
|
18
31
|
* @example
|
|
19
32
|
* ```tsx
|
|
@@ -21,27 +34,46 @@ import { useEffect, useMemo, useRef } from 'react';
|
|
|
21
34
|
* console.log(window.innerWidth, window.innerHeight);
|
|
22
35
|
* });
|
|
23
36
|
*
|
|
24
|
-
* useEventListener(
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* document
|
|
28
|
-
* );
|
|
37
|
+
* useEventListener(document, 'visibilitychange', () => {
|
|
38
|
+
* console.log(document.visibilityState);
|
|
39
|
+
* });
|
|
29
40
|
*
|
|
30
41
|
* const buttonRef = useRef<HTMLButtonElement>(null);
|
|
31
|
-
* useEventListener(
|
|
42
|
+
* useEventListener(buttonRef.current, 'click', () => console.log('click'));
|
|
32
43
|
* ```
|
|
33
44
|
*
|
|
34
45
|
* @ignore
|
|
35
46
|
*/
|
|
47
|
+
export function useEventListener<K extends keyof WindowEventMap>(
|
|
48
|
+
eventName: K,
|
|
49
|
+
handler: (this: Window, event: WindowEventMap[K]) => void,
|
|
50
|
+
options?: AddEventListenerOptions | boolean,
|
|
51
|
+
): void;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @see {@linkcode useEventListener}
|
|
55
|
+
* @ignore
|
|
56
|
+
*/
|
|
57
|
+
export function useEventListener<K extends keyof WindowEventMap>(
|
|
58
|
+
...args: UseEventListenerOverloadArgs<WindowEventMap, K, Window>
|
|
59
|
+
): void;
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* @see {@linkcode useEventListener}
|
|
63
|
+
* @ignore
|
|
64
|
+
*/
|
|
65
|
+
export function useEventListener<K extends keyof DocumentEventMap>(
|
|
66
|
+
...args: UseEventListenerOverloadArgs<DocumentEventMap, K, Document>
|
|
67
|
+
): void;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @see {@linkcode useEventListener}
|
|
71
|
+
* @ignore
|
|
72
|
+
*/
|
|
36
73
|
export function useEventListener<
|
|
37
74
|
K extends keyof HTMLElementEventMap,
|
|
38
75
|
T extends HTMLElement,
|
|
39
|
-
>(
|
|
40
|
-
eventName: K,
|
|
41
|
-
handler: (this: NoInfer<T>, event: HTMLElementEventMap[K]) => void,
|
|
42
|
-
element: T | null,
|
|
43
|
-
options?: boolean | AddEventListenerOptions,
|
|
44
|
-
): void;
|
|
76
|
+
>(...args: UseEventListenerOverloadArgs<HTMLElementEventMap, K, T>): void;
|
|
45
77
|
|
|
46
78
|
/**
|
|
47
79
|
* @see {@linkcode useEventListener}
|
|
@@ -50,12 +82,7 @@ export function useEventListener<
|
|
|
50
82
|
export function useEventListener<
|
|
51
83
|
K extends keyof SVGElementEventMap,
|
|
52
84
|
T extends SVGElement,
|
|
53
|
-
>(
|
|
54
|
-
eventName: K,
|
|
55
|
-
handler: (this: NoInfer<T>, event: SVGElementEventMap[K]) => void,
|
|
56
|
-
element: T | null,
|
|
57
|
-
options?: boolean | AddEventListenerOptions,
|
|
58
|
-
): void;
|
|
85
|
+
>(...args: UseEventListenerOverloadArgs<SVGElementEventMap, K, T>): void;
|
|
59
86
|
|
|
60
87
|
/**
|
|
61
88
|
* @see {@linkcode useEventListener}
|
|
@@ -64,42 +91,36 @@ export function useEventListener<
|
|
|
64
91
|
export function useEventListener<
|
|
65
92
|
K extends keyof MathMLElementEventMap,
|
|
66
93
|
T extends MathMLElement,
|
|
67
|
-
>(
|
|
68
|
-
eventName: K,
|
|
69
|
-
handler: (this: NoInfer<T>, event: MathMLElementEventMap[K]) => void,
|
|
70
|
-
element: T | null,
|
|
71
|
-
options?: boolean | AddEventListenerOptions,
|
|
72
|
-
): void;
|
|
94
|
+
>(...args: UseEventListenerOverloadArgs<MathMLElementEventMap, K, T>): void;
|
|
73
95
|
|
|
74
96
|
/**
|
|
75
97
|
* @see {@linkcode useEventListener}
|
|
76
|
-
* @ignore
|
|
77
98
|
*/
|
|
78
|
-
export function useEventListener<K extends keyof
|
|
99
|
+
export function useEventListener<K extends keyof WindowEventMap>(
|
|
79
100
|
eventName: K,
|
|
80
|
-
handler: (this:
|
|
81
|
-
|
|
82
|
-
options?: boolean | AddEventListenerOptions,
|
|
101
|
+
handler: (this: Window, event: WindowEventMap[K]) => void,
|
|
102
|
+
options?: AddEventListenerOptions | boolean,
|
|
83
103
|
): void;
|
|
84
104
|
|
|
85
105
|
/**
|
|
86
106
|
* @see {@linkcode useEventListener}
|
|
87
|
-
* @ignore
|
|
88
107
|
*/
|
|
89
|
-
export function useEventListener<
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
options?:
|
|
108
|
+
export function useEventListener<T extends EventTarget>(
|
|
109
|
+
target: T | null,
|
|
110
|
+
eventName: string,
|
|
111
|
+
handler: (this: NoInfer<T>, event: Event) => void,
|
|
112
|
+
options?: AddEventListenerOptions | boolean,
|
|
94
113
|
): void;
|
|
95
114
|
|
|
96
115
|
/**
|
|
97
|
-
* Adds `handler` as a listener for the event `eventName` of `
|
|
116
|
+
* Adds `handler` as a listener for the event `eventName` of `target` with the
|
|
98
117
|
* provided `options` applied
|
|
99
118
|
*
|
|
100
|
-
* If `
|
|
119
|
+
* If `target` is not provided, `window` is used instead.
|
|
101
120
|
*
|
|
102
|
-
* If `
|
|
121
|
+
* If `target` is `null`, no event listener is added. This is useful when
|
|
122
|
+
* working with DOM element refs, or when the event listener needs to be removed
|
|
123
|
+
* temporarily.
|
|
103
124
|
*
|
|
104
125
|
* @example
|
|
105
126
|
* ```tsx
|
|
@@ -107,29 +128,29 @@ export function useEventListener<K extends keyof WindowEventMap>(
|
|
|
107
128
|
* console.log(window.innerWidth, window.innerHeight);
|
|
108
129
|
* });
|
|
109
130
|
*
|
|
110
|
-
* useEventListener(
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
* document
|
|
114
|
-
* );
|
|
131
|
+
* useEventListener(document, 'visibilitychange', () => {
|
|
132
|
+
* console.log(document.visibilityState);
|
|
133
|
+
* });
|
|
115
134
|
*
|
|
116
135
|
* const buttonRef = useRef<HTMLButtonElement>(null);
|
|
117
|
-
* useEventListener(
|
|
136
|
+
* useEventListener(buttonRef.current, 'click', () => console.log('click'));
|
|
118
137
|
* ```
|
|
119
138
|
*/
|
|
120
|
-
export function useEventListener<T extends EventTarget>(
|
|
121
|
-
eventName: string,
|
|
122
|
-
handler: (this: NoInfer<T>, event: Event) => void,
|
|
123
|
-
element?: T | null,
|
|
124
|
-
options?: boolean | AddEventListenerOptions,
|
|
125
|
-
): void;
|
|
126
|
-
|
|
127
139
|
export function useEventListener(
|
|
128
|
-
|
|
129
|
-
handler: (this: EventTarget, event: Event) => void,
|
|
130
|
-
element?: EventTarget | null,
|
|
131
|
-
options?: boolean | AddEventListenerOptions,
|
|
140
|
+
...args: UseEventListenerArgsWithoutTarget | UseEventListenerArgsWithTarget
|
|
132
141
|
) {
|
|
142
|
+
let eventName: string;
|
|
143
|
+
let handler: (this: EventTarget, event: Event) => void;
|
|
144
|
+
let target: EventTarget | null | undefined;
|
|
145
|
+
let options: AddEventListenerOptions | boolean | undefined;
|
|
146
|
+
|
|
147
|
+
if (typeof args[0] === 'string') {
|
|
148
|
+
[eventName, handler, options] = args as UseEventListenerArgsWithoutTarget;
|
|
149
|
+
} else {
|
|
150
|
+
[target, eventName, handler, options] =
|
|
151
|
+
args as UseEventListenerArgsWithTarget;
|
|
152
|
+
}
|
|
153
|
+
|
|
133
154
|
const handlerRef = useRef(handler);
|
|
134
155
|
handlerRef.current = handler;
|
|
135
156
|
|
|
@@ -147,24 +168,34 @@ export function useEventListener(
|
|
|
147
168
|
);
|
|
148
169
|
|
|
149
170
|
useEffect(() => {
|
|
150
|
-
if (
|
|
171
|
+
if (target === null) {
|
|
151
172
|
// No element has been attached to the ref yet
|
|
152
173
|
return;
|
|
153
174
|
}
|
|
154
175
|
|
|
155
|
-
|
|
156
|
-
const targetElement = element ?? window;
|
|
176
|
+
const definedTarget = target ?? window;
|
|
157
177
|
|
|
158
|
-
// Create event listener that calls handler function stored in ref
|
|
159
178
|
const listener: typeof handler = function (event) {
|
|
160
179
|
handlerRef.current.call(this, event);
|
|
161
180
|
};
|
|
162
181
|
|
|
163
|
-
|
|
182
|
+
definedTarget.addEventListener(eventName, listener, memoizedOptions);
|
|
164
183
|
|
|
165
|
-
// Remove event listener on cleanup
|
|
166
184
|
return () => {
|
|
167
|
-
|
|
185
|
+
definedTarget.removeEventListener(eventName, listener, memoizedOptions);
|
|
168
186
|
};
|
|
169
|
-
}, [eventName,
|
|
187
|
+
}, [eventName, target, memoizedOptions]);
|
|
170
188
|
}
|
|
189
|
+
|
|
190
|
+
type UseEventListenerArgsWithoutTarget = [
|
|
191
|
+
eventName: string,
|
|
192
|
+
handler: (event: Event) => void,
|
|
193
|
+
options?: AddEventListenerOptions | boolean | undefined,
|
|
194
|
+
];
|
|
195
|
+
|
|
196
|
+
type UseEventListenerArgsWithTarget = [
|
|
197
|
+
target: EventTarget | null,
|
|
198
|
+
eventName: string,
|
|
199
|
+
handler: (event: Event) => void,
|
|
200
|
+
options?: AddEventListenerOptions | boolean | undefined,
|
|
201
|
+
];
|
|
@@ -11,6 +11,55 @@ import type { useReducerWithDeps } from './useReducerWithDeps.js';
|
|
|
11
11
|
* This hook is designed in the most general way possible in order to cover all
|
|
12
12
|
* imaginable use cases.
|
|
13
13
|
*
|
|
14
|
+
* @example
|
|
15
|
+
* Sometimes, React's immutability constraints mean too much unnecessary copying
|
|
16
|
+
* of data when new data arrives at a high frequency. In such cases, it might be
|
|
17
|
+
* desirable to ignore the constraints by embracing imperative patterns.
|
|
18
|
+
* Here is an example of a scenario where that can make sense:
|
|
19
|
+
*
|
|
20
|
+
* ```tsx
|
|
21
|
+
* type SensorData = { timestamp: number; value: number };
|
|
22
|
+
* const sensorDataRef = useRef<SensorData[]>([]);
|
|
23
|
+
* const mostRecentSensorDataTimestampRef = useRef<number>(0);
|
|
24
|
+
*
|
|
25
|
+
* const [forceUpdate, updateCount] = useForceUpdate();
|
|
26
|
+
* // Limiting the frequency of forced re-renders with some throttle function:
|
|
27
|
+
* const throttledForceUpdateRef = useRef(throttle(forceUpdate));
|
|
28
|
+
*
|
|
29
|
+
* useEffect(() => {
|
|
30
|
+
* return sensorDataObservable.subscribe((data: SensorData) => {
|
|
31
|
+
* // Imagine new sensor data arrives every 1 millisecond. If we were following
|
|
32
|
+
* // React's immutability rules by creating a new array every time, the data
|
|
33
|
+
* // that's already there would have to be copied many times before the new
|
|
34
|
+
* // data would even get a chance to be reflected in the UI for the first time
|
|
35
|
+
* // because it typically takes much longer than 1 millisecond for a new frame
|
|
36
|
+
* // to be displayed. To prevent the waste of computational resources, we just
|
|
37
|
+
* // mutate the existing array every time instead:
|
|
38
|
+
* sensorDataRef.current.push(data);
|
|
39
|
+
* if (data.timestamp > mostRecentSensorDataTimestampRef.current) {
|
|
40
|
+
* mostRecentSensorDataTimestampRef.current = data.timestamp;
|
|
41
|
+
* }
|
|
42
|
+
* throttledForceUpdateRef.current();
|
|
43
|
+
* });
|
|
44
|
+
* }, []);
|
|
45
|
+
*
|
|
46
|
+
* const [timeWindow, setTimeWindow] = useState(1000);
|
|
47
|
+
* const selectedSensorData = useMemo(
|
|
48
|
+
* () => {
|
|
49
|
+
* // Keep this line if you don't want to disable the
|
|
50
|
+
* // react-hooks/exhaustive-deps ESLint rule:
|
|
51
|
+
* updateCount;
|
|
52
|
+
* const threshold = mostRecentSensorDataTimestampRef.current - timeWindow;
|
|
53
|
+
* return sensorDataRef.current.filter(
|
|
54
|
+
* ({ timestamp }) => timestamp >= threshold,
|
|
55
|
+
* );
|
|
56
|
+
* },
|
|
57
|
+
* // sensorDataRef.current always references the same array, so listing it as a
|
|
58
|
+
* // dependency is pointless. Instead, updateCount should be used:
|
|
59
|
+
* [updateCount, timeWindow],
|
|
60
|
+
* );
|
|
61
|
+
* ```
|
|
62
|
+
*
|
|
14
63
|
* @param callback An optional callback function to call during renders that
|
|
15
64
|
* were triggered with `forceUpdate()`
|
|
16
65
|
*
|
|
@@ -32,11 +81,11 @@ import type { useReducerWithDeps } from './useReducerWithDeps.js';
|
|
|
32
81
|
export function useForceUpdate(callback?: () => void): [() => void, bigint] {
|
|
33
82
|
// It is very unlikely that the number of updates will exceed
|
|
34
83
|
// Number.MAX_SAFE_INTEGER, but not impossible. That is why we use bigints.
|
|
35
|
-
const [
|
|
36
|
-
const
|
|
37
|
-
if (
|
|
38
|
-
|
|
84
|
+
const [updateCount, forceUpdate] = useReducer((prev) => prev + 1n, 0n);
|
|
85
|
+
const updateCountRef = useRef(updateCount);
|
|
86
|
+
if (updateCount !== updateCountRef.current) {
|
|
87
|
+
updateCountRef.current = updateCount;
|
|
39
88
|
callback?.();
|
|
40
89
|
}
|
|
41
|
-
return [forceUpdate,
|
|
90
|
+
return [forceUpdate, updateCount];
|
|
42
91
|
}
|
|
@@ -18,6 +18,9 @@ export type ActionDispatch<ActionArg extends AnyActionArg> = (
|
|
|
18
18
|
* `useReducer` hook with an additional dependency array `deps` that resets the
|
|
19
19
|
* state to `initialState` when dependencies change
|
|
20
20
|
*
|
|
21
|
+
* For motivation and examples, see
|
|
22
|
+
* https://github.com/facebook/react/issues/33041.
|
|
23
|
+
*
|
|
21
24
|
* ### On linter support
|
|
22
25
|
*
|
|
23
26
|
* The `react-hooks/exhaustive-deps` ESLint rule doesn't support hooks where
|
|
@@ -26,7 +29,7 @@ export type ActionDispatch<ActionArg extends AnyActionArg> = (
|
|
|
26
29
|
* possible, we don't want to artificially change the parameter's position.
|
|
27
30
|
* Therefore, there will be no warnings about missing dependencies.
|
|
28
31
|
* Because of that, additional caution is advised!
|
|
29
|
-
* Be sure to check no dependencies are missing from the `deps` array.
|
|
32
|
+
* Be sure to check that no dependencies are missing from the `deps` array.
|
|
30
33
|
*
|
|
31
34
|
* Related issue: {@link https://github.com/facebook/react/issues/25443}.
|
|
32
35
|
*
|
|
@@ -19,6 +19,41 @@ import { useForceUpdate } from './useForceUpdate.js';
|
|
|
19
19
|
* `useState` hook with an additional dependency array `deps` that resets the
|
|
20
20
|
* state to `initialState` when dependencies change
|
|
21
21
|
*
|
|
22
|
+
* For motivation and more examples, see
|
|
23
|
+
* https://github.com/facebook/react/issues/33041.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```tsx
|
|
27
|
+
* type Activity = 'breakfast' | 'exercise' | 'swim' | 'board games' | 'dinner';
|
|
28
|
+
*
|
|
29
|
+
* const timeOfDayOptions = ['morning', 'afternoon', 'evening'] as const;
|
|
30
|
+
* type TimeOfDay = (typeof timeOfDayOptions)[number];
|
|
31
|
+
*
|
|
32
|
+
* const activityOptionsByTimeOfDay: {
|
|
33
|
+
* [K in TimeOfDay]: [Activity, ...Activity[]];
|
|
34
|
+
* } = {
|
|
35
|
+
* morning: ['breakfast', 'exercise', 'swim'],
|
|
36
|
+
* afternoon: ['exercise', 'swim', 'board games'],
|
|
37
|
+
* evening: ['board games', 'dinner'],
|
|
38
|
+
* };
|
|
39
|
+
*
|
|
40
|
+
* export function Example() {
|
|
41
|
+
* const [timeOfDay, setTimeOfDay] = useState<TimeOfDay>('morning');
|
|
42
|
+
*
|
|
43
|
+
* const activityOptions = activityOptionsByTimeOfDay[timeOfDay];
|
|
44
|
+
* const [activity, setActivity] = useStateWithDeps<Activity>(
|
|
45
|
+
* (prev) => {
|
|
46
|
+
* // Make sure activity is always valid for the current timeOfDay value,
|
|
47
|
+
* // but also don't reset it unless necessary:
|
|
48
|
+
* return prev && activityOptions.includes(prev) ? prev : activityOptions[0];
|
|
49
|
+
* },
|
|
50
|
+
* [activityOptions],
|
|
51
|
+
* );
|
|
52
|
+
*
|
|
53
|
+
* return '...';
|
|
54
|
+
* }
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
22
57
|
* @param initialState The value to which the state is set when the component is
|
|
23
58
|
* mounted or dependencies change
|
|
24
59
|
*
|
|
@@ -32,12 +67,10 @@ export function useStateWithDeps<S>(
|
|
|
32
67
|
initialState: S | ((previousState?: S) => S),
|
|
33
68
|
deps: DependencyList,
|
|
34
69
|
): [S, Dispatch<SetStateAction<S>>] {
|
|
35
|
-
// It would be possible to use useState instead of
|
|
36
|
-
//
|
|
37
|
-
//
|
|
38
|
-
//
|
|
39
|
-
// re-renders, the state is stored in a ref and an
|
|
40
|
-
// update is triggered via forceUpdate below when necessary
|
|
70
|
+
// It would be possible to use useState instead of useRef to store the state,
|
|
71
|
+
// however this would trigger re-renders whenever the state is reset due to a
|
|
72
|
+
// change in dependencies. In order to avoid these re-renders, the state is
|
|
73
|
+
// stored in a ref, and updates are triggered with forceUpdate when necessary.
|
|
41
74
|
const state = useRef(undefined as S);
|
|
42
75
|
|
|
43
76
|
const prevDeps = useRef(deps);
|
|
@@ -20,6 +20,8 @@ export type RestrictedContext<T> =
|
|
|
20
20
|
: { Provider: Provider<T>; displayName: string };
|
|
21
21
|
|
|
22
22
|
/**
|
|
23
|
+
* The return type of {@linkcode createSafeContext}
|
|
24
|
+
*
|
|
23
25
|
* @see {@linkcode createSafeContext}
|
|
24
26
|
*/
|
|
25
27
|
export type SafeContext<DisplayName extends string, T> = {
|
|
@@ -33,24 +35,55 @@ export type SafeContext<DisplayName extends string, T> = {
|
|
|
33
35
|
* type and a hook that returns the current context value if one was provided,
|
|
34
36
|
* or throws an error otherwise
|
|
35
37
|
*
|
|
38
|
+
* The advantages over vanilla `createContext` are that no default value has to
|
|
39
|
+
* be provided, and that a meaningful context name is displayed in dev tools
|
|
40
|
+
* instead of generic `Context.Provider`.
|
|
41
|
+
*
|
|
36
42
|
* @example
|
|
37
43
|
* ```tsx
|
|
38
|
-
*
|
|
44
|
+
* enum Direction {
|
|
45
|
+
* Up,
|
|
46
|
+
* Down,
|
|
47
|
+
* Left,
|
|
48
|
+
* Right,
|
|
49
|
+
* }
|
|
50
|
+
*
|
|
51
|
+
* // Before
|
|
52
|
+
* const DirectionContext = createContext<Direction | undefined>(undefined);
|
|
53
|
+
* DirectionContext.displayName = 'DirectionContext';
|
|
54
|
+
*
|
|
55
|
+
* const useDirection = () => {
|
|
56
|
+
* const direction = useContext(DirectionContext);
|
|
57
|
+
* if (direction === undefined) {
|
|
58
|
+
* // Called outside of a <DirectionContext.Provider> boundary!
|
|
59
|
+
* // Or maybe undefined was explicitly provided as the context value
|
|
60
|
+
* // (ideally that shouldn't be allowed, but it is because we had to include
|
|
61
|
+
* // undefined in the context type so as to provide a meaningful default)
|
|
62
|
+
* throw new Error('No DirectionContext value was provided');
|
|
63
|
+
* }
|
|
64
|
+
* // Thanks to the undefined check, the type is now narrowed down to Direction
|
|
65
|
+
* return direction;
|
|
66
|
+
* };
|
|
67
|
+
*
|
|
68
|
+
* // After
|
|
69
|
+
* const { DirectionContext, useDirection } =
|
|
70
|
+
* createSafeContext<Direction>()('Direction'); // That's it :)
|
|
39
71
|
*
|
|
40
72
|
* const Parent = () => (
|
|
41
|
-
*
|
|
73
|
+
* // Providing undefined as the value is not allowed 👍
|
|
74
|
+
* <Direction.Provider value={Direction.Up}>
|
|
42
75
|
* <Child />
|
|
43
|
-
* </
|
|
76
|
+
* </Direction.Provider>
|
|
44
77
|
* );
|
|
45
78
|
*
|
|
46
|
-
* const Child = () =>
|
|
79
|
+
* const Child = () => `Current direction: ${Direction[useDirection()]}`;
|
|
47
80
|
* ```
|
|
48
81
|
*
|
|
49
82
|
* @returns
|
|
50
83
|
* A function that accepts a single string argument `displayName` (e.g.
|
|
51
|
-
* `"
|
|
52
|
-
* - ``` `${displayName}Context` ``` (e.g. `
|
|
53
|
-
* - ``` `use${displayName}` ``` (e.g. `
|
|
84
|
+
* `"Direction"`) and returns an object with the following properties:
|
|
85
|
+
* - ``` `${displayName}Context` ``` (e.g. `DirectionContext`): the context
|
|
86
|
+
* - ``` `use${displayName}` ``` (e.g. `useDirection`): a hook that returns the
|
|
54
87
|
* current context value if one was provided, or throws an error otherwise
|
|
55
88
|
*/
|
|
56
89
|
export function createSafeContext<T = never>() {
|