โš›๏ธ React Intersection Observer ๐Ÿ‘€ Hook ๐Ÿช.

1843 ๋‹จ์–ด observerintersectionhookreact
MDN์— ๋”ฐ๋ฅด๋ฉด Intersection Observer API๋Š” ๋น„๋™๊ธฐ์‹์œผ๋กœ ๊ด€์ฐฐํ•  ์ˆ˜ ์žˆ๋Š” ๋ฐฉ๋ฒ•์„ ์ œ๊ณตํ•ฉ๋‹ˆ๋‹ค.
๋Œ€์ƒ ์š”์†Œ์™€ ์ƒ์œ„ ์š”์†Œ ๋˜๋Š” ์ตœ์ƒ์œ„ ๋ฌธ์„œ์˜ ๊ต์ฐจ์ ์—์„œ ๋ณ€๊ฒฝ๋ฉ๋‹ˆ๋‹ค.

๋ณต์žกํ•ด ๋ณด์ด์ง€๋งŒ React์—์„œ๋Š” ๊ฐ„๋‹จํ•œ ํ›„ํฌ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๊ต์ฐจ๋ฅผ ๋‹ฌ์„ฑํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
๋ช…์‹ฌํ•ด์•ผ ํ•  ์œ ์ผํ•œ ๊ฒƒ์€ '๋Œ€์ƒ ์š”์†Œ'๋ฅผ ๊ด€์ฐฐ์ž์—๊ฒŒ ์ „๋‹ฌํ•ด์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.
useRef() ์‚ฌ์šฉ

const targetMiddle = React.useRef();
const targetTop = React.useRef();




<h3 ref={targetTop}>TOP</h3>
<h3 ref={targetMiddle}>Middle</h3>



ํ›…



ํ›„ํฌ๋Š” ๋งค์šฐ ๊ฐ„๋‹จํ•ฉ๋‹ˆ๋‹ค
๋Œ€์ƒ ์š”์†Œ๋ฅผ ์ธ์ˆ˜๋กœ ํ—ˆ์šฉํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋‚ด๋ณด๋‚ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
๊ธฐ๋ณธ์ ์œผ๋กœ ์ž„๊ณ„๊ฐ’์€ 0์œผ๋กœ ์„ค์ •๋˜์ง€๋งŒ ํ•„์š”์— ๋”ฐ๋ผ ์˜ต์…˜์„ ๊ฐ€์ง€๊ณ  ๋†€ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
_isIntersecting _entry ์†์„ฑ์„ ์‚ฌ์šฉํ•˜์—ฌ ์ƒํƒœ ์„ค์ •

export function useObserver(ref) {

    const [isIntersecting, setIsIntersecting] = React.useState(false);

     // OPTIONS
     const options = {
        // root: target.current,
        rootMargin: '0px',
        threshold: 0.5, // A threshold of 1.0 means that when 100% of the target is visible within the element specified by the root option, the callback is invoked.
    };
    // Observer
    const observer = new IntersectionObserver(([entry]) => setIsIntersecting(entry.isIntersecting),options);

    // Use Effect
    React.useEffect(() => {

        observer.observe(ref.current)
        // DISCONNECT 
        return () => observer.disconnect()

    }, []);
    // Return
    return isIntersecting
  };



useEffect ๋‚ด๋ถ€์—์„œ _disconnect _ ๋ฉ”์„œ๋“œ๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ๋Œ€์ƒ ์š”์†Œ ๊ด€์ฐฐ์„ ์ค‘์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
๋งˆ์ง€๋ง‰์œผ๋กœ ์ฐธ ๋˜๋Š” ๊ฑฐ์ง“์ด ๋  ์ˆ˜ ์žˆ๋Š” ์ƒํƒœ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.
์ด ๊ฐ’์„ ๊ธฐ๋ฐ˜์œผ๋กœ ์˜ˆ๋ฅผ ๋“ค์–ด ๋น„๋””์˜ค๋ฅผ ํ‘œ์‹œํ•˜๊ฑฐ๋‚˜ ์ˆจ๊น€์œผ๋กœ์จ vDom์„ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
๋Œ€์ƒ ์š”์†Œ๊ฐ€ ๋ณด์ด๋ฉด ํ•œ๊ณ„๋Š” ๋‹น์‹ ์˜ ์ƒ์ƒ๋ ฅ์ž…๋‹ˆ๋‹ค!

์ด ๋น„๋””์˜ค ๊ฐ€์ด๋“œ์—์„œ ๋งค์šฐ ๊ฐ„๋‹จํ•œ ๊ตฌํ˜„, ์ข‹์€ ๊ด€์ฐฐ์„ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค ๐Ÿ‘€ ...

Video Guide
๐Ÿ†— ๐Ÿ‘‹

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ