Skip to content

Commit 3ab5e39

Browse files
authored
Fix useScrollLock instances issue (#2860)
* fix instances issue * add changeset
1 parent 3dd75c9 commit 3ab5e39

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

.changeset/poor-ads-hunt.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@sumup-oss/circuit-ui": patch
3+
---
4+
5+
Fixed an issue with simultaneous instances of the `useScrollLock` hook.

packages/circuit-ui/hooks/useScrollLock/useScrollLock.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515

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

18+
let instanceCount = 0;
19+
1820
export const useScrollLock = (isLocked: boolean): void => {
1921
const scrollValue = useRef<string>();
2022

@@ -27,6 +29,18 @@ export const useScrollLock = (isLocked: boolean): void => {
2729
body.style.width = '';
2830
window.scrollTo(0, Number.parseInt(scrollY || '0', 10) * -1);
2931
}, []);
32+
33+
useEffect(() => {
34+
instanceCount += 1;
35+
36+
return () => {
37+
instanceCount -= 1;
38+
if (instanceCount === 0) {
39+
restoreScroll();
40+
}
41+
};
42+
}, [restoreScroll]);
43+
3044
useEffect(() => {
3145
if (isLocked) {
3246
scrollValue.current = `${window.scrollY}px`;
@@ -39,11 +53,8 @@ export const useScrollLock = (isLocked: boolean): void => {
3953
body.style.position = 'fixed';
4054
body.style.width = `${bodyWidth}px`;
4155
body.style.top = `-${scrollY}`;
42-
} else {
56+
} else if (instanceCount === 1) {
4357
restoreScroll();
4458
}
45-
return () => {
46-
restoreScroll();
47-
};
4859
}, [isLocked, restoreScroll]);
4960
};

0 commit comments

Comments
 (0)