11import { useEffect , useRef , useState } from 'react' ;
22
3- export const useIntersectionObserver = ( options = { } ) => {
3+ interface IntersectionOptions {
4+ threshold ?: number ;
5+ rootMargin ?: string ;
6+ mobileThreshold ?: number ;
7+ mobileRootMargin ?: string ;
8+ }
9+
10+ export const useIntersectionObserver = ( options : IntersectionOptions = { } ) => {
411 const elementRef = useRef < HTMLDivElement > ( null ) ;
512 const [ inView , setInView ] = useState ( false ) ;
13+ const [ isMobile , setIsMobile ] = useState ( false ) ;
14+
15+ useEffect ( ( ) => {
16+ const checkMobile = ( ) => {
17+ setIsMobile ( window . innerWidth < 768 ) ; // 768px is typical mobile breakpoint
18+ } ;
19+
20+ checkMobile ( ) ;
21+ window . addEventListener ( 'resize' , checkMobile ) ;
22+
23+ return ( ) => window . removeEventListener ( 'resize' , checkMobile ) ;
24+ } , [ ] ) ;
625
726 useEffect ( ( ) => {
827 const element = elementRef . current ;
928 if ( ! element ) return ;
1029
11- const observer = new IntersectionObserver ( ( entries ) => {
12- entries . forEach ( ( entry ) => {
13- setInView ( entry . isIntersecting ) ;
14- } ) ;
15- } , options ) ;
30+ const observer = new IntersectionObserver (
31+ ( entries ) => {
32+ entries . forEach ( ( entry ) => {
33+ setInView ( entry . isIntersecting ) ;
34+ } ) ;
35+ } ,
36+ {
37+ threshold : isMobile
38+ ? options . mobileThreshold ?? options . threshold
39+ : options . threshold ,
40+ rootMargin : isMobile
41+ ? options . mobileRootMargin ?? options . rootMargin
42+ : options . rootMargin ,
43+ }
44+ ) ;
1645
1746 observer . observe ( element ) ;
1847
@@ -21,7 +50,7 @@ export const useIntersectionObserver = (options = {}) => {
2150 observer . unobserve ( element ) ;
2251 }
2352 } ;
24- } , [ options ] ) ;
53+ } , [ options , isMobile ] ) ;
2554
2655 return { elementRef, inView } ;
2756} ;
0 commit comments