Skip to content

Commit 48fd313

Browse files
committed
Add useRefWithInit
1 parent 70c19a1 commit 48fd313

File tree

2 files changed

+19
-6
lines changed

2 files changed

+19
-6
lines changed
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import { useRef } from 'react';
2+
3+
// useRef() does not support init function like useMemo().
4+
export default function useRefWithInit<T>(fn: () => T): ReturnType<typeof useRef<T>> {
5+
const initializedRef = useRef(false);
6+
const ref = useRef<T>();
7+
8+
if (!initializedRef.current) {
9+
ref.current = fn();
10+
initializedRef.current = true;
11+
}
12+
13+
return ref;
14+
}

packages/component/src/providers/ClipboardWritePermissionWithStable/private/useStableStateHook.ts

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1-
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type SetStateAction } from 'react';
1+
import { useCallback, useEffect, useMemo, useState, type Dispatch, type SetStateAction } from 'react';
22
import { createPropagation } from 'use-propagate';
33
import { useRefFrom } from 'use-ref-from';
44

5+
import useRefWithInit from './useRefWithInit';
6+
57
export default function useStableStateHook<T>(value: T): () => readonly [T];
68

79
export default function useStableStateHook<T>(
@@ -13,13 +15,9 @@ export default function useStableStateHook<T>(
1315
value: T,
1416
setValue?: Dispatch<SetStateAction<T>> | undefined
1517
): () => readonly [T, Dispatch<SetStateAction<T>>] | readonly [T] {
16-
const propagationRef = useRef<ReturnType<typeof createPropagation<T>>>();
18+
const propagationRef = useRefWithInit<ReturnType<typeof createPropagation<T>>>(() => createPropagation<T>());
1719
const valueRef = useRefFrom(value);
1820

19-
if (!propagationRef.current) {
20-
propagationRef.current = createPropagation<T>();
21-
}
22-
2321
const {
2422
current: { usePropagate, useListen }
2523
} = propagationRef;
@@ -28,6 +26,7 @@ export default function useStableStateHook<T>(
2826

2927
useEffect(() => propagate(value), [propagate, value]);
3028

29+
// One-off variable to hack around ESLint rules without disabling react-hooks/rules-of-hooks.
3130
const useHook = () => {
3231
const [propagatedValue, setPropagatedValue] = useState<T>(valueRef.current);
3332

0 commit comments

Comments
 (0)