diff --git a/apps/desktop/src/app/hooks/use-on-profile-switch.test.tsx b/apps/desktop/src/app/hooks/use-on-profile-switch.test.tsx new file mode 100644 index 0000000000..5be75409e2 --- /dev/null +++ b/apps/desktop/src/app/hooks/use-on-profile-switch.test.tsx @@ -0,0 +1,24 @@ +import { act, cleanup, renderHook } from '@testing-library/react' +import { atom } from 'nanostores' +import { StrictMode } from 'react' +import { afterEach, expect, it, vi } from 'vitest' + +vi.mock('@/store/profile', () => ({ $activeGatewayProfile: atom('default') })) + +import { $activeGatewayProfile } from '@/store/profile' + +import { useOnProfileSwitch } from './use-on-profile-switch' + +afterEach(cleanup) + +it('ignores StrictMode effect replay and reacts only to real profile changes', () => { + const onSwitch = vi.fn() + const { rerender } = renderHook(() => useOnProfileSwitch(onSwitch), { wrapper: StrictMode }) + expect(onSwitch).not.toHaveBeenCalled() + rerender() + expect(onSwitch).not.toHaveBeenCalled() + act(() => $activeGatewayProfile.set('other')) + expect(onSwitch).toHaveBeenCalledTimes(1) + act(() => $activeGatewayProfile.set('default')) + expect(onSwitch).toHaveBeenCalledTimes(2) +}) diff --git a/apps/desktop/src/app/hooks/use-on-profile-switch.ts b/apps/desktop/src/app/hooks/use-on-profile-switch.ts index dfdfd84f2c..6f3ca5061e 100644 --- a/apps/desktop/src/app/hooks/use-on-profile-switch.ts +++ b/apps/desktop/src/app/hooks/use-on-profile-switch.ts @@ -8,16 +8,17 @@ import { $activeGatewayProfile } from '@/store/profile' * when the backend the app talks to swaps underneath a still-mounted view. */ export function useOnProfileSwitch(onSwitch: () => void): void { const profile = useStore($activeGatewayProfile) - const first = useRef(true) + const previousProfile = useRef(profile) // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { - if (first.current) { - first.current = false - + // StrictMode replays mount effects without changing the profile. Counting + // effect runs would clear a seeded settings draft and leave it loading. + if (previousProfile.current === profile) { return } + previousProfile.current = profile onSwitch() // Fire on profile change only; onSwitch identity is intentionally ignored. // eslint-disable-next-line react-hooks/exhaustive-deps