@@ -510,33 +510,34 @@ export function useIdle(ms = 1000 * 60) {
510510}
511511
512512export 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 ;
515514 const [ entry , setEntry ] = React . useState ( null ) ;
516515
517- React . useEffect ( ( ) => {
518- const node = ref ?. current ;
519-
520- if ( ! node || typeof IntersectionObserver !== "function" ) {
521- return ;
522- }
516+ const previousObserver = React . useRef ( null ) ;
523517
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+ }
530524
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+ ) ;
532532
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+ ) ;
538539
539- return [ ref , entry ] ;
540+ return [ customRef , entry ] ;
540541}
541542
542543export function useIsClient ( ) {
0 commit comments