Skip to content

Commit 6cafb3c

Browse files
authored
Merge pull request #12 from FanchenBao/fanchen/fix_memory_leak
Fix memory leak issue by explicitly clean up contentRef upon unmount
2 parents ea4f2ad + e4dba62 commit 6cafb3c

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

src/index.tsx

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,19 @@ const AutoScrolling = ({
3131
const [isAutoScrolling, setIsAutoScrolling] = React.useState(false);
3232
const [dividerWidth, setDividerWidth] = React.useState(endPaddingWidth);
3333
const offsetX = React.useRef(new Animated.Value(0));
34-
let contentRef: any;
34+
const contentRef = React.useRef(0);
35+
36+
React.useEffect(() => {
37+
// Clean up to avoid calling measureContainerView after unmount.
38+
return () => (contentRef.current = 0);
39+
});
3540

3641
function measureContainerView(event: LayoutChangeEvent) {
3742
const newContainerWidth = event.nativeEvent.layout.width;
3843
if (containerWidth.current === newContainerWidth) return;
3944
containerWidth.current = newContainerWidth;
40-
if (!contentRef) return;
41-
contentRef.measure((fx: number, fy: number, width: number) => {
45+
if (!contentRef.current) return;
46+
contentRef.current.measure((fx: number, fy: number, width: number) => {
4247
checkContent(width, fx);
4348
});
4449
}
@@ -87,7 +92,7 @@ const AutoScrolling = ({
8792
const childrenWithProps = React.cloneElement(children, {
8893
...childrenProps,
8994
onLayout: measureContentView,
90-
ref: (ref: any) => (contentRef = ref),
95+
ref: (ref: any) => (contentRef.current = ref),
9196
});
9297

9398
return (

0 commit comments

Comments
 (0)