Skip to content

useScrollLock: concurrent overlays corrupt body scroll state when closed out of order #4787

Closed

Description

@alex-js-ltd

useScrollLock (packages/core/src/hooks/useScrollLock.ts) has no coordination between instances — each call independently snapshots document.body.style when its own effect mounts and restores that exact snapshot on cleanup. I confirmed this directly against the hook (two concurrent renderHook(() => useScrollLock(true)) calls, unmounted out of order — see regression tests below).

The same hook is called, unmodified, by Dialog, Lightbox, and by Drawer/BottomSheet in packages/lab — since none of them wrap or alter the hook's behavior, the same bug applies to any pairing of these opened concurrently (e.g. a Lightbox opened from within a Dialog).

Failure sequence with two overlays open at once:

  1. Overlay A opens, saves the true original body style, locks the body.
  2. Overlay B opens on top, saves A's already-locked style as its "original."
  3. A closes first (B still open) → A restores the true original → body unlocks while B is still open.
  4. B closes → B restores what it saved in step 2 (hidden/fixed) → body is now stuck locked permanently, with nothing left open to undo it.

Regression tests (fail against main):

it('stays locked while a second overlay is still open, even if the first closes out of order', () => {
  vi.spyOn(window, 'scrollTo').mockImplementation(() => {});

  const first = renderHook(() => useScrollLock(true));
  const second = renderHook(() => useScrollLock(true));

  first.unmount();

  expect(document.body.style.position).toBe('fixed');
  expect(document.body.style.overflow).toBe('hidden');

  second.unmount();
});

it('fully restores the body once every overlay has closed, regardless of close order', () => {
  vi.spyOn(window, 'scrollTo').mockImplementation(() => {});

  const first = renderHook(() => useScrollLock(true));
  const second = renderHook(() => useScrollLock(true));

  first.unmount();
  second.unmount();

  expect(document.body.style.position).toBe('');
  expect(document.body.style.overflow).toBe('');
  expect(document.body.style.top).toBe('');
  expect(document.body.style.left).toBe('');
  expect(document.body.style.right).toBe('');
});

I've opened #4788 with regression tests and a proposed fix.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions