Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsubscribe from event listener react hooks

In a class-based react component you could simply do;

componentWillUnmount() {
  window.removeEventListener('resize', this.resizeHandler);
}

Although I am unsure how to do this in a Function Based Component with React Hooks?

In my application, I perform the function below on a button click in a Component LoginCard.

const handleLogin = (email, password) => {
  loginService.login(email, password)
    .then((response) => {
      if (!response.error) {
        props.history.push("/");
      }
    });
}

And I wrap the export of LoginCard in a withRouter function from react-router-dom to redirect to the route address.

export default withRouter(LoginCard);

Inside the LoginCard Component I have a Tabs Component which has the event listener in the useEffect hook.

useEffect(() => {
      setUnderLineStyle(getUnderlineStyle());
      window.addEventListener("resize", _.throttle(() => { 
         setUnderLineStyle(getUnderlineStyle())}, 
         300), 
         {passive:true});
   }, [props]);

However, when I click that button in LoginCard and get redirected to / and then resize the window, the function inside the resize event lister setUnderLineStyle(getUnderlineStyle()) gets called.

I have tried to add the following in useEffect but setUnderLineStyle(getUnderlineStyle()) still gets called on resize.

return () => window.removeEventListener("resize", _.throttle(() => { 
                setUnderLineStyle(getUnderlineStyle())}, 
                300), 
                {passive:true});

Any ideas? Even around a better redirect method to get to / via react-router-dom or how to effectively unsubscribe from event listeners?

like image 293
mcclosa Avatar asked Mar 21 '19 14:03

mcclosa


People also ask

How do you remove the event listener in React hooks?

Add the event listener in the useEffect hook. Return a function from the useEffect hook. Use the removeEventListener method to remove the event listener when the component unmounts.

Should I remove event listeners React?

Always cleanup your event listeners. Do this with window. removeEventListener when your component unmounts. By cleaning up, you'll avoid listening to events multiple times and memory leaks.

How do I get rid of addEventListener Appstate?

Use the remove() method on the EventSubscription returned by addEventListener() .

Where would you unsubscribe from a subscription in useEffect?

This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. The instruction is pretty clear and straightforward, "cancel all subscriptions and asynchronous tasks in a useEffect cleanup function".


1 Answers

Make a second useEffect solely for the use of unmounting. Empty dependencies in useEffect make it effectively function as a componentDidMount, and the return of that effectively functions as a componentWillUnmount.

useEffect(() => {
    // Do mounting stuff here

    return () => {
        // Do unmounting stuff here
    };
}, []);
like image 50
ApplePearPerson Avatar answered Oct 12 '22 12:10

ApplePearPerson