Sometimes, we need to clean up resources used in the React useEffect
hook when a component unmounts.
In this article, we’ll look at how to clean up resources used in the React useEffect
hook when a component unmounts.
Run React Hooks useEffect Cleanup Code When Component Unmounts
We can return a function in the useEffect
callback to return a function that runs our clean up code.
For example, we can write:
const { useState, useEffect } = React;
const ForExample = () => {
const [name, setName] = useState("");
const [username, setUsername] = useState("");
useEffect(
() => {
console.log("do something");
},
[username]
);
useEffect(() => {
return () => {
console.log("cleaned up");
};
}, []);
const handleName = e => {
const { value } = e.target;
setName(value);
};
const handleUsername = e => {
const { value } = e.target;
setUsername(value);
};
return (
<div>
<div>
<input value={name} onChange={handleName} />
<input value={username} onChange={handleUsername} />
</div>
</div>
);
};
We have our change event handlers.
And we have our useEffect
calls.
They all have their own callbacks.
The first one watches for changes in the username
function.
In the 2nd one, the callback returns a function that runs code when the component unmounts.
Conclusion
We can return a function in the useEffect
callback to return a function that runs our clean up code.