@@ -72,16 +72,27 @@ export const useOnInView = <TElement extends Element>(
72
72
| undefined
73
73
| ReturnType < IntersectionChangeEffect < TElement > > ;
74
74
75
- // enter: intersectionsStateTrigger = true
76
- // leave: intersectionsStateTrigger = false
75
+ // trigger " enter" : intersectionsStateTrigger = true
76
+ // trigger " leave" : intersectionsStateTrigger = false
77
77
const intersectionsStateTrigger = trigger !== "leave" ;
78
78
79
79
const destroyInviewObserver = observe (
80
80
element ,
81
81
( inView , entry ) => {
82
+ // Call the callback when the element is in view (if trigger is "enter")
83
+ // Call the callback when the element is out of view (if trigger is "leave")
84
+ if ( inView === intersectionsStateTrigger ) {
85
+ callbackCleanup = onIntersectionChangeRef . current ( entry ) ;
86
+
87
+ // if there is no cleanup function returned from the callback
88
+ // and triggerOnce is true, the observer can be destroyed immediately
89
+ if ( triggerOnce && ! callbackCleanup ) {
90
+ destroyInviewObserver ( ) ;
91
+ }
92
+ }
82
93
// Call cleanup when going out of view (if trigger is "enter")
83
94
// Call cleanup when going in view (if trigger is "leave")
84
- if ( inView !== intersectionsStateTrigger ) {
95
+ else {
85
96
if ( callbackCleanup ) {
86
97
callbackCleanup ( entry ) ;
87
98
callbackCleanup = undefined ;
@@ -91,16 +102,6 @@ export const useOnInView = <TElement extends Element>(
91
102
destroyInviewObserver ( ) ;
92
103
}
93
104
}
94
- } else {
95
- // Call the callback when the element is in view (if trigger is "enter")
96
- // Call the callback when the element is out of view (if trigger is "leave")
97
- callbackCleanup = onIntersectionChangeRef . current ( entry ) ;
98
-
99
- // if there is no cleanup function returned from the callback
100
- // and triggerOnce is true, the observer can be destroyed immediately
101
- if ( triggerOnce && ! callbackCleanup ) {
102
- destroyInviewObserver ( ) ;
103
- }
104
105
}
105
106
} ,
106
107
{
0 commit comments