Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions src/components/Switch/Switch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,33 @@ const Switch = ({
...rest
}: Props) => {
const theme = useInternalTheme(themeOverrides);

// Internal state is needed to fix #4789 where Switch is inside a Portal
const [internalValue, setInternalValue] = React.useState<boolean>(() =>
typeof value === 'boolean' ? value : false
);

React.useEffect(() => {
if (typeof value === 'boolean' && value !== internalValue) {
setInternalValue(value);
}
}, [value, internalValue]);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Inefficient State Synchronization in useEffect

The useEffect hook includes internalValue in its dependency array. This causes the effect to re-evaluate when the internal state changes, even if the external value prop, which the effect is meant to synchronize with, remains the same. This leads to unnecessary re-renders.

Fix in Cursor Fix in Web

Comment on lines +76 to +80
Copy link

@gkueny gkueny Oct 29, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
React.useEffect(() => {
if (typeof value === 'boolean' && value !== internalValue) {
setInternalValue(value);
}
}, [value, internalValue]);
React.useEffect(() => {
setInternalValue(oldValue => {
if (typeof value === 'boolean' && value !== oldValue) {
return value;
}
return oldValue;
});
}, [value]);


const { checkedColor, onTintColor, thumbTintColor } = getSwitchColor({
theme,
disabled,
value,
value: internalValue,
color,
});

const handleValueChange = React.useCallback(
(newValue: boolean) => {
setInternalValue(newValue);
onValueChange?.(newValue);
},
[onValueChange]
);

const props =
version && version.major === 0 && version.minor <= 56
? {
Expand All @@ -96,13 +116,15 @@ const Switch = ({

return (
<NativeSwitch
value={value}
value={internalValue}
disabled={disabled}
onValueChange={disabled ? undefined : onValueChange}
onValueChange={disabled ? undefined : handleValueChange}
{...props}
{...rest}
/>
);
};

Switch.displayName = 'Switch';

export default Switch;