Skip to content

Commit 97c4fa0

Browse files
committed
refactor(use-composition-input): reuse useSingleton
1 parent 2daf81e commit 97c4fa0

File tree

1 file changed

+9
-17
lines changed

1 file changed

+9
-17
lines changed

src/use-composition-input/index.ts

+9-17
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,17 @@
11
import 'client-only';
2-
import { useCallback, useRef } from 'react';
2+
import { useCallback } from 'react';
3+
import { useSingleton } from '../use-singleton';
34

45
export type UseCompositionInputCallback = (value: string) => void;
56
export type UseCompositionInputReturnKey = 'onChange' | 'onCompositionStart' | 'onCompositionEnd';
67
export type UseCompositionInputReturn = Pick<JSX.IntrinsicElements['input'], UseCompositionInputReturnKey>;
78

89
/** @see https://foxact.skk.moe/use-composition-input */
910
export const useCompositionInput = (cb: UseCompositionInputCallback): UseCompositionInputReturn => {
10-
// @ts-expect-error -- We are using singleton approach here, to prevent repeated initialization.
11-
const internalState: React.MutableRefObject<{
12-
/** is"C"ompositioning */ c: boolean,
13-
/** is"E"mitted */ e: boolean
14-
}> = useRef();
15-
16-
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- it will be undefined only on first render
17-
if (!internalState.current) {
18-
internalState.current = {
19-
/** is"C"ompositioning */ c: false,
20-
/** is"E"mitted */ e: false
21-
};
22-
}
11+
const internalState = useSingleton(() => ({
12+
/** is"C"ompositioning */ c: false,
13+
/** is"E"mitted */ e: false
14+
}));
2315

2416
const onChange = useCallback((e: React.ChangeEvent<HTMLInputElement> | React.CompositionEvent<HTMLInputElement>) => {
2517
if ('value' in e.target) {
@@ -32,12 +24,12 @@ export const useCompositionInput = (cb: UseCompositionInputCallback): UseComposi
3224
internalState.current.e = false;
3325
}
3426
}
35-
}, [cb]);
27+
}, [cb, internalState]);
3628

3729
const onCompositionStart = useCallback<React.CompositionEventHandler<HTMLInputElement>>(() => {
3830
internalState.current.c = true;
3931
internalState.current.e = false;
40-
}, []);
32+
}, [internalState]);
4133

4234
const onCompositionEnd = useCallback<React.CompositionEventHandler<HTMLInputElement>>((e) => {
4335
internalState.current.c = false;
@@ -48,7 +40,7 @@ export const useCompositionInput = (cb: UseCompositionInputCallback): UseComposi
4840
if (!internalState.current.e) {
4941
onChange(e);
5042
}
51-
}, [onChange]);
43+
}, [internalState, onChange]);
5244

5345
return {
5446
onChange,

0 commit comments

Comments
 (0)