Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

React 18 breaks some usage of useThrottle #2343

Open
jpwilliams opened this issue Jun 1, 2022 · 0 comments
Open

React 18 breaks some usage of useThrottle #2343

jpwilliams opened this issue Jun 1, 2022 · 0 comments

Comments

@jpwilliams
Copy link

jpwilliams commented Jun 1, 2022

What is the current behavior?

React 18 has introduced some new Strict Mode behaviours that results in components unmounting and remounting whenever it mounts for the first time, restoring the previous state on the second mount.

For useThrottle, this results in the hook believing a timer has already been set and it will wait indefinitely for the now-removed timer to call back. It appears this is caused by the timer being cleared via clearTimeout but not unset.

Steps to reproduce it and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have extra dependencies other than react-use. Paste the link to your JSFiddle or CodeSandbox example below:

I'll venture to add a repro repo if needed.

What is the expected behavior?

The hook fully clears away the timer on unmount and can remount and start it again.

A little about versions:

  • OS: Ubuntu
  • Browser (vendor and version): Microsoft Edge Version 101.0.1210.53 (Official build) (64-bit)
  • React: 18
  • react-use: 17.3.2
  • Did this worked in the previous package version? Not with React 18.

That particular fix is an easy one; we change useThrottle.ts:30:

// from
timeout.current && clearTimeout(timeout.current);

// to
if (timeout.current) {
  clearTimeout(timeout.current);
  timeout.current = undefined;
}

With this, when the state is restored it understands that the timer has been fully cleared away from the initial mount and we're good to go.

In terms of tests, we may be a bit blocked. It looks like @testing-library/react-hooks may be deprecated before they add React 18 support. @testing-library/react@13 seems to take it's place by adding their own renderHook function, but this also drops support for React 17 in the process. 😬

Related

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant