From f20a7079ce51add7e15696da926632cdc92a57b8 Mon Sep 17 00:00:00 2001 From: Hai Le Date: Wed, 17 Apr 2024 21:20:09 +1000 Subject: [PATCH] fix: improve onChange callback performance --- .gitignore | 2 ++ components/ViewPortDetector.tsx | 17 +++++++++++++---- 2 files changed, 15 insertions(+), 4 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..97008e5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +node_modules +yarn.lock \ No newline at end of file diff --git a/components/ViewPortDetector.tsx b/components/ViewPortDetector.tsx index 8ad59b2..27d5d4a 100644 --- a/components/ViewPortDetector.tsx +++ b/components/ViewPortDetector.tsx @@ -1,5 +1,5 @@ import React, { useContext, useEffect, useRef } from "react"; -import { Dimensions, View, ViewStyle } from "react-native"; +import { Dimensions, Platform, View, ViewStyle } from "react-native"; import { LayoutRectangle } from "../types"; import { checkInViewPort } from "../utils"; import { ViewPortDetectorContext } from "./ViewPortDetectorContext"; @@ -51,6 +51,8 @@ export const ViewPortDetector: React.FC = ({ ...props }) => { const view = useRef(null); + const lastInViewPortValue = useRef(false); + const { parentLayout } = useContext(ViewPortDetectorContext); const parentLayoutRef = useRef({ x: 0, @@ -104,17 +106,24 @@ export const ViewPortDetector: React.FC = ({ if (newValue && runOnce) { clearInterval(interval); } - onChange(newValue); + + // Only call onChange callback when inViewPort value changed + if (newValue !== lastInViewPortValue.current) { + onChange(newValue) + lastInViewPortValue.current = newValue + } } ); }, frequency); return () => { clearInterval(interval); }; - }, []); + }, [onChange]); return ( - + // Having collapsable={false} will disable view flattening on Android which is a workaronud to fix the issue with measure() on android + // https://github.com/facebook/react-native/issues/29712 + {children} );