Skip to content

Commit

Permalink
feat: debounce message draft state updates to reduce zustand/immer st…
Browse files Browse the repository at this point in the history
…ore writes on Messages page
  • Loading branch information
danditomaso committed Jan 25, 2025
1 parent fe2b76e commit d0ca24a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 6 deletions.
28 changes: 22 additions & 6 deletions src/components/PageComponents/Messages/MessageInput.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { debounce } from "@app/core/utils/debounce";
import { Button } from "@components/UI/Button.tsx";
import { Input } from "@components/UI/Input.tsx";
import { useDevice } from "@core/stores/deviceStore.ts";
import type { Types } from "@meshtastic/js";
import { SendIcon } from "lucide-react";
import { useCallback, useState, useMemo } from "react";



export interface MessageInputProps {
to: Types.Destination;
Expand All @@ -20,10 +24,15 @@ export const MessageInput = ({
setMessageDraft,
hardware,
} = useDevice();

const myNodeNum = hardware.myNodeNum;
const [localDraft, setLocalDraft] = useState(messageDraft);

const sendText = async (message: string) => {
const debouncedSetMessageDraft = useMemo(
() => debounce(setMessageDraft, 300),
[setMessageDraft]
);

const sendText = useCallback(async (message: string) => {
await connection
?.sendText(message, to, true, channel)
.then((id) =>
Expand All @@ -46,6 +55,12 @@ export const MessageInput = ({
e.error,
),
);
}, [channel, connection, myNodeNum, setMessageState, to]);

const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
setLocalDraft(newValue);
debouncedSetMessageDraft(newValue);
};

return (
Expand All @@ -54,7 +69,8 @@ export const MessageInput = ({
className="w-full"
onSubmit={(e) => {
e.preventDefault();
sendText(messageDraft);
sendText(localDraft);
setLocalDraft("");
setMessageDraft("");
}}
>
Expand All @@ -64,8 +80,8 @@ export const MessageInput = ({
autoFocus={true}
minLength={1}
placeholder="Enter Message"
value={messageDraft}
onChange={(e) => setMessageDraft(e.target.value)}
value={localDraft}
onChange={handleInputChange}
/>
</span>
<Button type="submit">
Expand All @@ -75,4 +91,4 @@ export const MessageInput = ({
</form>
</div>
);
};
};
13 changes: 13 additions & 0 deletions src/core/utils/debounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
type Callback<Args extends unknown[]> = (...args: Args) => void;

export function debounce<Args extends unknown[]>(
callback: Callback<Args>,
wait: number
): Callback<Args> {
let timeoutId: ReturnType<typeof setTimeout>;

return (...args: Args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => callback(...args), wait);
};
}

0 comments on commit d0ca24a

Please sign in to comment.