
React Effect Hook
While updating state, we sometimes have side effects that might need to happen along with each change. The Effect Hook allows us to perform side effects in the function components. In order words, Effect Hook comes as an alternative for ComponentDidMount()
, ComponentDidUpdate()
and ComponentWillUnmount()
lifecycle methods.
Let's have a look at an example with useEffect
hook:
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
// Same functionality as componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `Button Clicked ${count} times`;
});
return (
<div>
<p>Button clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
The useEffect
method will be triggered as the component mounts, unmounts, and everytime the component re-renders.
In React Components, there are two types of side effects:
- Effects without Cleanup
- Effects with Cleanup
Effects without Cleanup
Some requests like Network requests, logging, manual DOM Manipulations are some examples of effects that don't require a cleanup. We can say that because we can run them and can immediately forget about them. The effects without cleanup doesn't block the browser from updating the screen.
Effects with Cleanup
There are some effects which require cleanup after updation. Example can be like if we want to setup some subscription to some external data source, in order to avoid a memory leak we need to clean up memory. When the component unmounts, React performs a cleanup of memory. Now, as we know that with every render()
method the effect runs, and not just once. Therefore, it cleans up effects from the previous render before running the effects next time.