How to call useEffect React Hook on a component mount and unmount

With pure function React Components you're not allowed to use lifecycle methods like componentDidMount or componentWillUnmount.
These can be replaced with proper use of useEffect hook introduced in React version 16.8.
Here is the code that will run exactly once when a component is mounted and exactly once when it's supposed to be unmounted:
import { useEffect } from "React";
const ExampleComponent = () => {
useEffect(() => {
// Here goes the code you wish to run on mount
return () => {
// Here goes the code you wish to run on unmount
}
}, []);
...
}
It's crucial to pass an empty array as the second argument of useEffect function call. If you omit it or pass dependencies inside of array it won't work as intended.
Work with a team that keeps learning and building better software every day.
Related posts
Dive deeper into this topic with these related posts
You might also like
Discover more content from this category
Did you ever create a commit that you wish never happened? Let's be honest - we all did. There is an easy way to revert it in Git.
In this post, you'll learn how to easily redirect users to the previous path using the Navigation History plug.
Pattern-matching is one of the finest elixir-lang features. Whoever knows the power of this tool once, will want to use it forever.
