Should useInView return unobserve function?
When using useInView, I might want to trigger unobserve conditionally.
useInView currently returns ref, inView and entry. If it starts returning unobserve, it will enable clients to control when they want to stop observation.
If you set the skip option, it will destroy the IntersectionObserver.
If you want to trigger it from a callback, you would control it with a useState().
function Comp() {
const [skip, setSkip] = useState(false)
const { inView, ref } = useInView({ skip })
return <button ref={ref} onClick={() => setSkip(true)}>Inview: {inView.toString()}</button
}
If you need more control, I'd recommend using the observe() method directly.
Thanks. I'll check. Closing this ticket. will reopen if I still need any assistance.
I'm curious why the useInView return object doesn't include a consideration for adding an internal variable (unobserve) that allows users to directly use unobserve.
https://github.com/thebuilder/react-intersection-observer/blob/5af1a75c259537693f977bb0e3c8b7a1051e4bf8/src/useInView.tsx#L65
This way, it would eliminate the need for an additional useState resource.
function Comp() {
const [skip, setSkip] = useState(false)
const { inView, ref } = useInView({ skip })
return <button ref={ref} onClick={() => setSkip(true)}>Inview: {inView.toString()}</button
}
Most likely you'll have a reason for skipping the observer, and therefor it is a state of your component. In a real scenario, you would most likely already have that state, or you'd be able to calculate it during the render.
Being able to call unobserve directly would be an unreliable side-effect. How would you enable the hook again, in a clean manner? What happens if something causes it to reinstantiate the observer?