@@ -510,33 +510,34 @@ export function useIdle(ms = 1000 * 60) {
510
510
}
511
511
512
512
export function useIntersectionObserver ( options = { } ) {
513
- const { threshold = 1 , root = null , rootMargin = "0%" } = options ;
514
- const ref = React . useRef ( null ) ;
513
+ const { threshold = 1 , root = null , rootMargin = "0px" } = options ;
515
514
const [ entry , setEntry ] = React . useState ( null ) ;
516
515
517
- React . useEffect ( ( ) => {
518
- const node = ref ?. current ;
519
-
520
- if ( ! node || typeof IntersectionObserver !== "function" ) {
521
- return ;
522
- }
516
+ const previousObserver = React . useRef ( null ) ;
523
517
524
- const observer = new IntersectionObserver (
525
- ( [ entry ] ) => {
526
- setEntry ( entry ) ;
527
- } ,
528
- { threshold , root , rootMargin }
529
- ) ;
518
+ const customRef = React . useCallback (
519
+ ( node ) => {
520
+ if ( previousObserver . current ) {
521
+ previousObserver . current . disconnect ( ) ;
522
+ previousObserver . current = null ;
523
+ }
530
524
531
- observer . observe ( node ) ;
525
+ if ( node instanceof HTMLElement ) {
526
+ const observer = new IntersectionObserver (
527
+ ( [ entry ] ) => {
528
+ setEntry ( entry ) ;
529
+ } ,
530
+ { threshold, root, rootMargin }
531
+ ) ;
532
532
533
- return ( ) => {
534
- setEntry ( null ) ;
535
- observer . disconnect ( ) ;
536
- } ;
537
- } , [ threshold , root , rootMargin ] ) ;
533
+ observer . observe ( node ) ;
534
+ previousObserver . current = observer ;
535
+ }
536
+ } ,
537
+ [ threshold , root , rootMargin ]
538
+ ) ;
538
539
539
- return [ ref , entry ] ;
540
+ return [ customRef , entry ] ;
540
541
}
541
542
542
543
export function useIsClient ( ) {
0 commit comments