Skip to content

Commit 345881e

Browse files
authored
Merge pull request #607 from calinoracation/callie--reduce-rerenders
fix: remove extra useEffect used for resetting initial state
2 parents 9a390c9 + 6b905af commit 345881e

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

src/useInView.tsx

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -113,17 +113,22 @@ export function useInView({
113113
);
114114

115115
const entryTarget = state.entry?.target;
116-
117-
React.useEffect(() => {
118-
if (!ref && entryTarget && !triggerOnce && !skip) {
119-
// If we don't have a node ref, then reset the state (unless the hook is set to only `triggerOnce` or `skip`)
120-
// This ensures we correctly reflect the current state - If you aren't observing anything, then nothing is inView
121-
setState({
122-
inView: !!initialInView,
123-
entry: undefined,
124-
});
125-
}
126-
}, [ref, entryTarget, triggerOnce, skip, initialInView]);
116+
const previousEntryTarget = React.useRef<Element>();
117+
if (
118+
!ref &&
119+
entryTarget &&
120+
!triggerOnce &&
121+
!skip &&
122+
previousEntryTarget.current !== entryTarget
123+
) {
124+
// If we don't have a node ref, then reset the state (unless the hook is set to only `triggerOnce` or `skip`)
125+
// This ensures we correctly reflect the current state - If you aren't observing anything, then nothing is inView
126+
previousEntryTarget.current = entryTarget;
127+
setState({
128+
inView: !!initialInView,
129+
entry: undefined,
130+
});
131+
}
127132

128133
const result = [setRef, state.inView, state.entry] as InViewHookResponse;
129134

0 commit comments

Comments
 (0)