最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does React automatically clear Intervals on unmount? - Stack Overflow

programmeradmin1浏览0评论

I am starting an interval on ponentDidMount, storing the interval id returned, and using clearInterval on ponentWillUnmount, and I'm wondering if this is necessary.

Is there a garbage collection type thing that would kill the interval anyway when the ponent unmounts? I know it would kill it on a hard refresh, but wondering about SPA.

I am starting an interval on ponentDidMount, storing the interval id returned, and using clearInterval on ponentWillUnmount, and I'm wondering if this is necessary.

Is there a garbage collection type thing that would kill the interval anyway when the ponent unmounts? I know it would kill it on a hard refresh, but wondering about SPA.

Share Improve this question edited Feb 15, 2019 at 16:32 Patrick Hund 20.3k12 gold badges71 silver badges95 bronze badges asked Feb 15, 2019 at 16:28 jmcharguejmchargue 1797 bronze badges 2
  • There's no, because GC doesn't know if it should keep the interval or not – Andrey Commented Feb 15, 2019 at 16:29
  • 1 You have to clear it manually. You could abstract it into a HOC or even a custom hook if you find that you are repeating it in a lot of places. – Tholle Commented Feb 15, 2019 at 16:31
Add a ment  | 

3 Answers 3

Reset to default 6

No.

By design, a setInterval() would never be cleared automatically (unless you write a custom function that handles this internally).

When you create an interval using setInterval(), you're essentially saying that you want to run a function at regular intervals regardless of the scope that the interval was created. Even if the interval was created in a scope that is no longer reachable from anywhere, the interval will still run as the lifespan of an interval has no dependency on the scope that it is running in.

For this reason, it's important to always clear intervals to prevent functions from piling up on every mount, which will lead to memory leaks and probably unexpected side effects as you'll have multiple functions running on an interval that are each doing the same thing.

It is necessary to clearInterval on ponentDidUnmount. With the introduction of hooks in React this tedious process of storing the interval in a member variable and later clearing it has been made a lot easier. You are now able to return a function in useEffect to clear created intervals like so:

React.useEffect(() => {
  const interval = setInterval(() => console.log("something"));

  return () => clearInterval(interval);
}, []);

Please refer to the documentation for more information.

I have not looked it up, but I don't think so. Because React has no way of knowing that you have initialised a setInterval. I would remend that you clear it.

发布评论

评论列表(0)

  1. 暂无评论