I\'m building a form - series of questions (radio buttons) the user needs to answer before he can move on to the next screen. For fields validation I\'m using yup (npm packa
Here is a reusable hook that takes advantage of the IntersectionObserver API.
export default function useOnScreen(ref) {
const [isIntersecting, setIntersecting] = useState(false)
const observer = new IntersectionObserver(
([entry]) => setIntersecting(entry.isIntersecting)
)
useEffect(() => {
observer.observe(ref.current)
// Remove the observer as soon as the component is unmounted
return () => { observer.disconnect() }
}, [])
return isIntersecting
}
const DummyComponent = () => {
const ref = useRef()
const isVisible = useOnScreen(ref)
return {isVisible && `Yep, I'm on screen`}
}