What is useEffect?
The useEffect hook is a function that takes two arguments: a callback function (the effect) and an optional array of dependencies. The callback function contains the code that you want to run as a side effect. This can include fetching data from an API, updating the DOM, or subscribing to some external service. The dependencies array specifies when the effect should run; it lists the variables that, when changed, trigger the effect to re-run. If no dependencies are provided, the effect runs after every render.
In this example, the effect runs only once when the component mounts and cleans up when the component unmounts, because the dependencies array is empty.
Managing Side Effects
One of the primary uses of useEffect is to handle side effects such as data fetching. Before hooks, this was typically done in class components using lifecycle methods like componentDidMount and componentWillUnmount. With useEffect, you can achieve the same functionality in a more concise and readable manner.
Here, the useEffect hook fetches data when the component mounts and sets the state with the fetched data. Because the dependencies array is empty, this effect runs only once.
Cleanup Function
The cleanup function in useEffect is crucial for avoiding memory leaks and ensuring that resources are properly released. This function is optional but recommended, especially when dealing with subscriptions or timers.
In this example, a timer is set when the component mounts and cleared when the component unmounts.
Dependency Array
The dependency array is a powerful feature that allows you to control when your effect runs. When dependencies change, the effect re-runs. If no array is provided, the effect runs after every render, which can lead to performance issues. Providing the right dependencies ensures that your effect runs efficiently.
The effect above runs only when props.someProp or state.someState change.
That’s it. Hope you liked reading it :)