Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useEventListener logic is broken #56

Closed
mendrik opened this issue Nov 8, 2021 · 3 comments
Closed

useEventListener logic is broken #56

mendrik opened this issue Nov 8, 2021 · 3 comments

Comments

@mendrik
Copy link

mendrik commented Nov 8, 2021

usually in the first cycle the element ref is null and even though a ref element is present it will attach a listener to the window object. If ref is given it should wait until ref.current is available before attaching any events

@juliencrn
Copy link
Owner

juliencrn commented Nov 8, 2021

Hi @mendrik, good observation, but I think in this situation, we are done.

1_552z6hbX_b648DjpTLHZNg

Like you can see in this image, the ref is set before the effect was triggered, so, in other word, when we are in the useEffect callback, the ref must be OK.

You can make another test, create a component like this:

function Component() {
  const ref = useRef<null | HTMLDivElement>(null)

  useEffect(() => {
    console.log(ref)
  }, [])

  return <div ref={ref}>Example</div>
}

You can see in your console that in the only one console.log output, the ref is well-defined.

However, I can miss something, if you have an use-case with an issue, I'm open to re-check, any feedback is always welcome!

@mendrik
Copy link
Author

mendrik commented Nov 11, 2021

hmm maybe I debugged something wrong then. I thought it had attached the listener to window object. closing

@mendrik mendrik closed this as completed Nov 11, 2021
@schontz
Copy link

schontz commented Jan 22, 2024

I think making the target an optional parameter is a recipe for errors. Consider the following:

const LogClicks = forwardRef((props, ref) => {
  useEventListener('click', (e) => console.log(e.target), ref)
  return <div ref={ref}>{children}</div>
})

const UsesComponent = () => {
  return (<div><LogClicks>Hello</LogClicks></div>)
}

Since no ref is passed, it will remain null, and the click handler will be attached to the window. This is but one example of "what if the ref is not set?"

I believe it would be wiser to make the target required and never fallback to window, as it is easy to provide and prevents any confusion. This would also make the signature similar to the actual DOM method:

// If there is no target, no op
useEventListener(target, 'eventName', callbackFn)

// Looks about like:
target.addEventListener('eventName', callbackFn)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants