react-intersection-observer icon indicating copy to clipboard operation
react-intersection-observer copied to clipboard

Should useInView return unobserve function?

Open minaseem opened this issue 3 years ago • 4 comments

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.

minaseem avatar Mar 09 '23 05:03 minaseem

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.

thebuilder avatar Mar 09 '23 08:03 thebuilder

Thanks. I'll check. Closing this ticket. will reopen if I still need any assistance.

minaseem avatar Mar 09 '23 08:03 minaseem

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
}

lichunbin814 avatar May 29 '23 12:05 lichunbin814

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?

thebuilder avatar May 29 '23 14:05 thebuilder