useEffect hook clean-up function in React | React Interview Questions
Since the introduction of core React Hooks like useState and useEffect in 2018, developers have often puzzled over the name of one particular hook: "useEffect".
In functional programming, an "effect" typically refers to what's known as a "side effect".
The useEffect Hook in React serves as a tool to manage these side effects within components.
What are the side effects?
It could be anything from fetching data from a server to setting up event listeners or subscriptions. These actions typically occur in response to events like button clicks, form submissions, or component mounting and unmounting.
Common side effects include:
- Making a request to an API for data from a backend server
- To interact with browser APIs (that is, to use document or window directly)
- Using unpredictable timing functions like setTimeout or setInterval
React's useEffect allows functional components to execute code when the component mounts or when certain properties or states change. Additionally, it provides a mechanism for cleanup when the component is unmounted.
Why is cleaning up side effects important?
While handling side effects in React is moderately complex, issues arise when the component lifecycle intersects with the side-effect lifecycle.
For instance, completing a side effect and attempting to update the state of a dismounted component can lead to memory leaks, impacting performance and potentially causing system crashes.
The primary cause of memory leaks in React applications are mainly the result of not canceling subscriptions made when a component was mounted before the component is unmounted.
They cause many problems, including:
- Affects the performance by reducing the amount of memory available.
- Decreased application speed.
- and even system crashes.
Therefore, it’s necessary to eliminate memory leak problems.
What is the useEffect cleanup function?
It is a function of the useEffect hook that allows us to stop side effects that no longer need to be executed before our component is unmounted.
By returning a function within the useEffect hook, we can execute cleanup tasks such as stopping intervals or unsubscribing from subscriptions.
Consider the example of a countdown timer implemented with setInterval. Without proper cleanup, the interval would persist even after the component is unmounted, leading to memory leaks. By utilizing the cleanup function, we ensure that resources are released when they're no longer needed.
function Timer() { const [time, setTime] = useState(0); useEffect(() => { let interval = setInterval(() => setTime(prevTime => prevTime + 1), 1000); return () => { clearInterval(interval); // Cleanup: Clear the interval } }, []); return <div>{time}</div>; }
In this example, when the Timer component unmounts, the cleanup function inside useEffect will clear the interval, preventing any further updates to the component that no longer exists.
Remember, the cleanup function is essential in scenarios where you need to halt recurring side effects upon component unmounting, ensuring a clean and efficient application.