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?
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.
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.
Use the remove() method on the EventSubscription returned by addEventListener() .
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".
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
};
}, []);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With