Skip to content

Commit b861df0

Browse files
committed
More readable useEffect
1 parent a38dbc9 commit b861df0

File tree

1 file changed

+22
-17
lines changed

1 file changed

+22
-17
lines changed

ai/ai-react-app/src/components/Layout/LeftSidebar.tsx

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -31,34 +31,39 @@ const LeftSidebar: React.FC<LeftSidebarProps> = ({
3131
const [selectedPersonaId, setSelectedPersonaId] = useState<string>("default");
3232
const [customPersona, setCustomPersona] = useState<string>("");
3333

34-
// Effect to update systemInstruction when persona changes
35-
useEffect(() => {
34+
const newInstructionText = React.useMemo(() => {
3635
const selected = PREDEFINED_PERSONAS.find(
3736
(p) => p.id === selectedPersonaId,
3837
);
39-
if (!selected) return;
38+
// Should not happen with the dropdown, but good to have a fallback.
39+
if (!selected) return "";
4040

41-
const newInstructionText =
42-
selected.id === "custom" ? customPersona : selected.systemInstruction;
41+
return selected.id === "custom"
42+
? customPersona
43+
: selected.systemInstruction;
44+
}, [selectedPersonaId, customPersona]);
4345

46+
// Effect to update systemInstruction when persona changes
47+
useEffect(() => {
4448
setGenerativeParams((prevParams) => {
49+
const currentInstructionText =
50+
prevParams.systemInstruction?.parts?.[0]?.text ?? "";
51+
52+
// Only update if the text content has actually changed to prevent re-renders.
53+
if (newInstructionText === currentInstructionText) {
54+
return prevParams;
55+
}
56+
4557
const newSystemInstruction = newInstructionText
4658
? { parts: [{ text: newInstructionText }] }
4759
: undefined;
4860

49-
const currentInstructionText = prevParams.systemInstruction?.parts?.[0]?.text;
50-
51-
// Only update if the text content has actually changed.
52-
if ((newInstructionText || "") !== (currentInstructionText || "")) {
53-
return {
54-
...prevParams,
55-
systemInstruction: newSystemInstruction,
56-
};
57-
}
58-
// If no change, return the previous state to prevent re-render.
59-
return prevParams;
61+
return {
62+
...prevParams,
63+
systemInstruction: newSystemInstruction,
64+
};
6065
});
61-
}, [selectedPersonaId, customPersona, setGenerativeParams]);
66+
}, [newInstructionText, setGenerativeParams]);
6267

6368
// Define the available modes and their display names
6469
const modes: { id: AppMode; label: string }[] = [

0 commit comments

Comments
 (0)