Common side-effects that need cleanup in useEffect react hook

Common side-effects that need cleanup in useEffect react hook

There are common asynchronous side-effects that are recommended to cleanup.

When a side-effect completes and react tries to update the state of an already unmounted component. This leads to a React warning:

Warning: Can't perform a React state update on an unmounted component.        

1. Fetch requests

As already mentioned, it is recommended to abort the fetch request when the component unmount or updates.

No alt text provided for this image

Check the section?Canceling a fetch request?to find more information on how to properly cancel fetch requests.

2. Timer functions

When using?setTimeout(callback, time)?or?setInterval(callback, time)?timer functions, it's usually a good idea to clear them on unmount using the special?clearTimeout(timerId)?function.

No alt text provided for this image

3. Debounce and throttle

When debouncing or throttling event handlers in React, you may also want to make sure to clear any scheduled call of the debounced or throttled functions.

Usually the debounce and throttling implementations (e.g.?lodash.debounce,?lodash.throttle) provide a special method?cancel()?that you can call to stop the scheduled execution:

No alt text provided for this image

4. Web sockets

Another good candidate requiring cleanup are the?web sockets:

No alt text provided for this image

要查看或添加评论,请登录

Saura Mandal的更多文章

  • TS Tip

    TS Tip

    The problem is expressing how we want at least one key defined in an object, which can be quite common for stuff like…

  • Top 5 Reasons to choose NoSQL

    Top 5 Reasons to choose NoSQL

    P.S:- Not written by me, but I found it quite appealing.

    1 条评论
  • Published my npm package

    Published my npm package

    Hey folks! Despite of COVID-19 pandemic, I hope you are doing good. Stay safe.

    5 条评论
  • How we can prevent accidental modification of an object in JavaScript?

    How we can prevent accidental modification of an object in JavaScript?

    There are several methods to prevent modification of object which lock down object to ensure that no one, accidentally…

社区洞察

其他会员也浏览了