Skip to content

Commit 36ca7eb

Browse files
committed
perf(utils): wrap all funcs with useCallback
1 parent 701cfc6 commit 36ca7eb

File tree

2 files changed

+25
-14
lines changed

2 files changed

+25
-14
lines changed

.changes/optimize-usechat.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@matechat/react": patch:perf
3+
---
4+
5+
Wrap all `useChat` hooks with `useCallback` to avoid re-rendering.

src/utils/chat.ts

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useState } from "react";
1+
import { useCallback, useEffect, useState } from "react";
22
import type { InputOptions } from "./backend";
33
import type { Backend, Events, EventTypes, MessageParam } from "./types";
44

@@ -15,20 +15,26 @@ export function useChat(
1515
const [messages, setMessages] = useState<MessageParam[]>(initialMessages);
1616
const [isPending, setIsPending] = useState(false);
1717

18-
const input = async (prompt: string, options?: InputOptions) => {
19-
setIsPending(true);
20-
return backend.input(prompt, {
21-
messages,
22-
...options,
23-
});
24-
};
18+
const input = useCallback(
19+
async (prompt: string, options?: InputOptions) => {
20+
setIsPending(true);
21+
return backend.input(prompt, {
22+
messages,
23+
...options,
24+
});
25+
},
26+
[backend, messages],
27+
);
2528

26-
const on = <K extends EventTypes["type"]>(
27-
type: K,
28-
handler: Events[K],
29-
): (() => void) => {
30-
return backend.on(type, handler);
31-
};
29+
const on = useCallback(
30+
<K extends EventTypes["type"]>(
31+
type: K,
32+
handler: Events[K],
33+
): (() => void) => {
34+
return backend.on(type, handler);
35+
},
36+
[backend],
37+
);
3238

3339
useEffect(() => {
3440
const cleanCbs: (() => void)[] = [

0 commit comments

Comments
 (0)