We finish off our code by attaching our DOM ref to the actual DOM - by passing it as the ref prop to our. We can further optimize this by only calling it once - so as to not re-hide stuff we've already seen. We update the isVisible state variable by calling its setter - the setVisible function - with the value of entry.isIntersecting. ![]() ![]() Since we're only calling it once, we can assume the list will only ever contain a single element. The callback we pass into our observer is called with a list of entry objects - one for each time the observer.observe method is called. (Thanks to Sung Kim for pointing this out to me in the comment section!) That's what we're doing at the end of our useEffect implementation - we return a function that calls the unobserve method of our observer. Then, we tell the observer instance to observe our DOM node with observer.observe(domRef.current).īefore we're done, however, we need to clean up a bit - we need to remove the intersection listener from our DOM node whenever we unmount it! Luckily, we can return a cleanup function from useEffect, which will do this for us. whenever you scroll, zoom or new stuff comes on screen). ![]() We pass in a callback function, which will be called every time any DOM element registered to this observer changes its "status" (i.e. The setup of the intersection observer might look a bit unfamiliar, but it's pretty simple once you understand what's going on.įirst, we create a new instance of the IntersectionObserver class.
0 Comments
Leave a Reply. |