xnimorz / use-debounce

A debounce hook for react

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Stops working after Next.js Fast Refresh

nfantone opened this issue · comments

use-debounce stops working altogether after any changes to code are made in a Next.js project.

You can see a reproduction example here: https://codesandbox.io/s/hardcore-sara-ueu2k

Looks fine on first load, but doesn't call the input callback anymore after refresh.

After initial load

After [Fast Refresh] done

Some people are commenting similar situations over at the Next.js repo, experiencing breaking libs after they decided to rolled out their new "Fast Refresh" implementation. Oftentimes, these ended up being undiscovered bugs in the original libraries rather than a problem with Next.js itself.

Related Next.js issue: vercel/next.js#13268

commented

Hi @nfantone, thank you for the issue
The main tricky thing, why lots of third party libraries get crashed during fast-refresh updates, is fast-refresh re-calls (with cleanups) all useEffects inside custom hooks, components, etc.

I mean, the following code wouldn't work properly:

function MyComponent() {
  const isComponentUnmounted = useRef(false);
  useEffect(() => () => {isComponentUnmounted.current = true}, []); 
}

In the example above, we change ref to the truth inside useEffect cleanup function (which is handy to prevent unnecessary timers, callbacks, etc).
Usually, this code works correctly. But fast-refresh re-runs all useEffects, which leads to all cleanups call, and then useEffect would be called again.

I've fixed it, by publishing a new version: use-debounce@3.4.3.

Here is an example of such fixes, I hope it could be helpful: 2ac1732

Also, I've fixed the example by updating the version of use-debounce: https://codesandbox.io/s/hungry-architecture-4z46m?file=/pages/index.js (so that it works now)

Great stuff! It seems to work fine now. Many thanks for this, appreciated. Good work!