The following code will trigger a state change as soon as the element enters or leaves the viewport by scrolling
const dialog = useRef(), [visible, set] = useState(false) useEffect(() => { const observer = new IntersectionObserver((e) => { set(e[0].isIntersecting ? true : false) }, {root: null, rootMargin: '0px', threshold: 0}) observer.observe(dialog.current) return () => observer.disconnect() }, [dialog.current]) return <div ref={dialog}>my dialog</div> but if I try something like this
const observer = new IntersectionObserver((e) => { set(e[0].boundingClientRect.y <= 0 ? true : false) }, {root: null, rootMargin: '0px', threshold: 0}) the state gets updated only if a re-render is triggered, while I want it to trigger when I scroll the viewport, based on the boundingClientRect.y value of the observed element. the only way I found to make this work is by using window.onscroll event inside useEffect and putting the observer inside it but it doesn't look too good to me. Is there a different (and better) way than using window.onscroll ?