Skip to content

Commit 4e2905b

Browse files
committed
feat: optimize callback performance
1 parent 31f4edf commit 4e2905b

File tree

3 files changed

+26
-15
lines changed

3 files changed

+26
-15
lines changed

.changes/optimize-callback.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@matechat/react": patch:feat
3+
---
4+
5+
Optimize callback performance by using `useCallback`.

src/file-upload.tsx

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import clsx from "clsx";
22
import type React from "react";
3-
import { useRef } from "react";
3+
import { useCallback, useRef } from "react";
44
import { twMerge } from "tailwind-merge";
55
import Appendix from "./icons/appendix.svg";
66

@@ -14,11 +14,14 @@ export function FileUpload({
1414
...props
1515
}: FileUploadProps) {
1616
const fileInputRef = useRef<HTMLInputElement>(null);
17-
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
18-
const files = Array.from(e.target.files ?? []);
19-
onFilesSelect(files);
20-
if (fileInputRef.current) fileInputRef.current.value = "";
21-
};
17+
const handleChange = useCallback(
18+
(e: React.ChangeEvent<HTMLInputElement>) => {
19+
const files = Array.from(e.target.files ?? []);
20+
onFilesSelect(files);
21+
if (fileInputRef.current) fileInputRef.current.value = "";
22+
},
23+
[onFilesSelect],
24+
);
2225

2326
return (
2427
<button

src/sender.tsx

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import "./tailwind.css";
22

33
import clsx from "clsx";
4-
import { useEffect, useRef, useState } from "react";
4+
import { useCallback, useEffect, useRef, useState } from "react";
55
import { twMerge } from "tailwind-merge";
66
import PublishNew from "./icons/publish-new.svg";
77
import QuickStop from "./icons/quick-stop.svg";
@@ -109,7 +109,7 @@ export function Sender({
109109
}, [message, onMessageChange]);
110110

111111
const [controller, setController] = useState<AbortController | null>(null);
112-
const handleSend = () => {
112+
const handleSend = useCallback(() => {
113113
if (isSending) {
114114
setIsSending(false);
115115
return controller?.abort();
@@ -133,13 +133,16 @@ export function Sender({
133133
} else {
134134
onSend?.(newController);
135135
}
136-
};
137-
const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
138-
if (event.key === "Enter" && !event.shiftKey) {
139-
event.preventDefault();
140-
handleSend();
141-
}
142-
};
136+
}, [isSending, message, onSend, controller, input]);
137+
const handleKeyDown = useCallback(
138+
(event: React.KeyboardEvent<HTMLTextAreaElement>) => {
139+
if (event.key === "Enter" && !event.shiftKey) {
140+
event.preventDefault();
141+
handleSend();
142+
}
143+
},
144+
[handleSend],
145+
);
143146

144147
return (
145148
<div

0 commit comments

Comments
 (0)