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?
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
};
}, []);
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM