Skip to content

Commit

Permalink
Fix useScrollLock instances issue (#2860)
Browse files Browse the repository at this point in the history
* fix instances issue

* add changeset
  • Loading branch information
sirineJ authored Jan 10, 2025
1 parent 3dd75c9 commit 3ab5e39
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/poor-ads-hunt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@sumup-oss/circuit-ui": patch
---

Fixed an issue with simultaneous instances of the `useScrollLock` hook.
19 changes: 15 additions & 4 deletions packages/circuit-ui/hooks/useScrollLock/useScrollLock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@

import { useCallback, useEffect, useRef } from 'react';

let instanceCount = 0;

export const useScrollLock = (isLocked: boolean): void => {
const scrollValue = useRef<string>();

Expand All @@ -27,6 +29,18 @@ export const useScrollLock = (isLocked: boolean): void => {
body.style.width = '';
window.scrollTo(0, Number.parseInt(scrollY || '0', 10) * -1);
}, []);

useEffect(() => {
instanceCount += 1;

return () => {
instanceCount -= 1;
if (instanceCount === 0) {
restoreScroll();
}
};
}, [restoreScroll]);

useEffect(() => {
if (isLocked) {
scrollValue.current = `${window.scrollY}px`;
Expand All @@ -39,11 +53,8 @@ export const useScrollLock = (isLocked: boolean): void => {
body.style.position = 'fixed';
body.style.width = `${bodyWidth}px`;
body.style.top = `-${scrollY}`;
} else {
} else if (instanceCount === 1) {
restoreScroll();
}
return () => {
restoreScroll();
};
}, [isLocked, restoreScroll]);
};

0 comments on commit 3ab5e39

Please sign in to comment.