Is React able to automatically remove eventListeners from Refs when the component is destroyed?

Asked

Viewed 36 times

2

I have an input from a web components that to receive the value inputado, I must create a Ref for that input and add a eventListener, respectively:

 const nameInputRef = useRef(null)
 const [userName, setUserName] = useState('')

I created a useEffect so that when the component starts, it adds a eventListener in that ref. So I can manage my state change web component for my React component:

  useEffect(() => {
    nameInputRef.current.addEventListener(
      'inputChangedValue',
      ({ target: { value } }) => {
        fields.username.input.onChange(value)
      }
    )
  }, [])

My question is: React is able to automatically remove this Eventlistener when the component is destroyed?

1 answer

2


No. React is not able to determine that you have even created a Event Listener within a useEffect.

In this type of case, what you need to do is use a returned function of the callback of useEffect to remove the Listener you created previously, manually. Like this:

function handleEvent({ target: { value } }) {
  fields.username.input.onChange(value);
}

useEffect(() => {
  const current = nameInputRef.current;
  if (!current) { // Garante que não tentaremos acessar um valor nulo.
    return;
  }
  current.addEventListener('inputChangedValue', handleEvent);
  return () => current.removeEventListener('inputChangedValue', handleEvent);
}, []);

Notice I had to move the callback of the event for a function outside the useEffect. This is necessary because the removeEventListener expects a reference to the function so that you can remove the event.

Refer to documentation to understand how so-called effects with Cleanup.

If it’s something too repetitive, maybe it’s worth creating a hook customized to extract the Boilerplate repetitive to manage the addition and cleaning of Event listeners.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.