Ad

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?

Ad

Answer

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
    };
}, []);
Ad
source: stackoverflow.com
Ad