Since functional components are the way forward for React. It is important to learn the power of hooks. Hooks were introduced in React 16.8. They can help you achieve almost anything that a class component can do.
The Effect Hook or useEffect can replace lifecycle methods in functional component. In this post, I will cover 3 use cases where useEffect can be useful:
i) componentDidMount or Run useEffect only once on mount:
useEffect accepts two arguments first one is a function which runs after every render and second is a dependency array. (Will explain it below)
To make useEffect run only once. Pass an empty array as a second argument like the example below:
ii) componentWillUnmount or Run useEffect after unmount / render:
Although useEffect runs after the component gets unmounted. It also runs on every re-render. This provides us the opportunity to clean up the side effects before every render.
Similar to what I have explained in above example, Passing an empty array as second argument makes all the difference in deciding whether to run the useEffect before every render or only on unmount.
Here is an example of how to clean up the side effect after component unmounts:
iii) componentDidUpdate or Run useEffect on every render.
useEffect runs on every render by default. Important thing here is to consider if you really need to, because it may effect the performance.
However, here is an example of code which makes the code inside useEffect hook run every time the component re-renders.
This was just an introduction to useEffect Hooks. If you would like to learn more, I am a sharing a few links below to help you dig deeper into the topic.
Official Docs: https://reactjs.org/docs/hooks-effect.html
freeCodeCamp: https://www.freecodecamp.org/news/react-useeffect-absolute-beginners/
Featured Image by Ivan Jurilj on Unsplash