Skip to content

Commit d60a411

Browse files
authored
fix: incorrect visibility state on initial render - fixes #30
Updates PR #33 to add more checks and added missing state in useEffect's dependency array
1 parent 13bb87c commit d60a411

1 file changed

Lines changed: 17 additions & 3 deletions

File tree

src/VisibilitySensor.tsx

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,11 @@ const VisibilitySensor = forwardRef<VisibilitySensorRef, VisibilitySensorProps>(
5858
});
5959
const [lastValue, setLastValue] = useState<boolean | undefined>(undefined);
6060
const [active, setActive] = useState<boolean>(false);
61+
const hasMeasuredRef = useRef(false);
6162

6263
const measureInnerView = () => {
64+
/* Check if the sensor is active to prevent unnecessary measurements
65+
This avoids running measurements when the sensor is disabled or stopped */
6366
if (!active) return;
6467

6568
localRef.current?.measure(
@@ -88,6 +91,9 @@ const VisibilitySensor = forwardRef<VisibilitySensorRef, VisibilitySensorProps>(
8891
rectDimensions.rectHeight !== dimensions.rectHeight
8992
) {
9093
setRectDimensions(dimensions);
94+
/* Set hasMeasuredRef to true to indicate that a valid measurement has been taken
95+
This ensures visibility checks only proceed after initial measurement */
96+
hasMeasuredRef.current = true;
9197
}
9298
}
9399
);
@@ -100,7 +106,12 @@ const VisibilitySensor = forwardRef<VisibilitySensorRef, VisibilitySensorProps>(
100106
}, [active]);
101107

102108
const stopWatching = useCallback(() => {
103-
if (active) setActive(false);
109+
if (active) {
110+
setActive(false);
111+
/* Reset measurement state when stopping to ensure fresh measurements
112+
when the sensor is reactivated */
113+
hasMeasuredRef.current = false;
114+
}
104115
}, [active]);
105116

106117
useEffect(() => {
@@ -114,7 +125,10 @@ const VisibilitySensor = forwardRef<VisibilitySensorRef, VisibilitySensorProps>(
114125
}, [disabled, startWatching, stopWatching]);
115126

116127
useEffect(() => {
117-
if (!active) return;
128+
/* Ensure visibility checks only run when the sensor is active and
129+
at least one measurement has been completed. This prevents
130+
premature visibility calculations with invalid or stale dimensions */
131+
if (!active || !hasMeasuredRef.current) return;
118132

119133
const window: ScaledSize = Dimensions.get('window');
120134
const isVisible: boolean =
@@ -131,7 +145,7 @@ const VisibilitySensor = forwardRef<VisibilitySensorRef, VisibilitySensorProps>(
131145
}
132146
}
133147
// eslint-disable-next-line react-hooks/exhaustive-deps
134-
}, [rectDimensions, lastValue]);
148+
}, [rectDimensions, lastValue, active]);
135149

136150
return (
137151
<View ref={localRef} {...rest}>

0 commit comments

Comments
 (0)