乐闻世界logo
搜索文章和话题

How to clean up setInterval in useEffect using react hooks

1个答案

1

In React's useEffect hook, you can clean up setInterval by returning a cleanup function. This cleanup function is executed when the component unmounts or when the dependency array changes.

Here is an example demonstrating how to set up a timer in useEffect and clean it up when the component unmounts:

jsx
import React, { useState, useEffect } from 'react'; function TimerComponent() { const [count, setCount] = useState(0); useEffect(() => { // Create the timer const intervalId = setInterval(() => { setCount((prevCount) => prevCount + 1); // Update state }, 1000); // Return cleanup function return () => { clearInterval(intervalId); // Clean up the timer }; }, []); // Empty dependency array means this side effect runs only once on component mount return <div>Timer: {count} seconds</div>; } export default TimerComponent;

In this example, the useEffect hook sets up a timer that increments the count variable every second upon initial render. Since the dependency array is empty ([]), the side effect runs only once on mount, and the cleanup function returned is called when the component unmounts to clear the timer. This prevents the timer from running when the component is no longer visible, thus avoiding potential memory leaks.

2024年6月29日 12:07 回复

你的答案