Skip to content

Commit 9e03357

Browse files
committed
Get rid of useless useCallback
1 parent ba0a6ab commit 9e03357

File tree

2 files changed

+18
-19
lines changed

2 files changed

+18
-19
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ All properties except `onKey` are optional.
3939

4040
| Property | Description | Default value |
4141
|----------------------------------|----------------------------------------------------------------------------------------------------------------------|---------------|
42-
| `onKey` (required) | the function executed after a key event | n/a |
42+
| `onKey` (required) | the function executed after a key event. You're responsible for keeping is stable | n/a |
4343
| `type` | keyup or keydown | `'keydown'` |
4444
| `target` | the element you want to attach the event to: an **existing** DOM element, a CSS selector (you will need to add `tabIndex='0'` to your element, otherwise the event won't be caught), or a **React ref** (`RefObject<HTMLElement>`) — if a ref is passed and `.current` is `null`, the listener is silently skipped | `document` |
4545
| `preventInputConflict` | prevent onKey from firing if you have an onChange on an input, a textarea or a select | `false` |

src/keybinding.tsx

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { type RefObject, useCallback, useEffect } from 'react';
1+
import { type RefObject, useEffect } from 'react';
22

33
export type KeybindingProps = {
44
onKey: (e: KeyboardEvent) => void;
@@ -62,8 +62,12 @@ export default function Keybinding(props: KeybindingProps) {
6262
stopPropagation = false,
6363
} = props;
6464

65-
const onKeyEvent = useCallback(
66-
(e: KeyboardEvent) => {
65+
useEffect(() => {
66+
const actualTarget = getTarget(target);
67+
68+
if (!actualTarget) return;
69+
70+
const onKeyEvent = (e: KeyboardEvent) => {
6771
const target = e.target as HTMLElement | null;
6872

6973
if (target != null) {
@@ -86,27 +90,22 @@ export default function Keybinding(props: KeybindingProps) {
8690
onKey(e);
8791
}
8892
}
89-
},
90-
[
91-
preventDefault,
92-
stopPropagation,
93-
preventInputConflict,
94-
preventContentEditableConflict,
95-
onKey,
96-
],
97-
);
98-
99-
useEffect(() => {
100-
const actualTarget = getTarget(target);
101-
102-
if (!actualTarget) return;
93+
};
10394

10495
actualTarget.addEventListener(type, onKeyEvent as EventListener);
10596

10697
return () => {
10798
actualTarget.removeEventListener(type, onKeyEvent as EventListener);
10899
};
109-
}, [target, type, onKeyEvent]);
100+
}, [
101+
target,
102+
type,
103+
onKey,
104+
preventDefault,
105+
stopPropagation,
106+
preventInputConflict,
107+
preventContentEditableConflict,
108+
]);
110109

111110
return null;
112111
}

0 commit comments

Comments
 (0)