react-use icon indicating copy to clipboard operation
react-use copied to clipboard

fix: useThrottle useThrottleFn unmount issue in Next.js

Open johnnywang1994 opened this issue 3 years ago • 2 comments

Description

  • Env: next 13.1.1 + Typescript
  • React strictMode cause useThrottle, useThrottleFn unmount bug

Situation:

  • As is: click div but nothing print out in console.
  • To be: print text in console.
import { FC, useState } from 'react';
import { useThrottleFn } from 'react-use';

const RefreshPageButton: FC = () => {
  const [value, setVal] = useState(0);

  useThrottleFn(() => {
    console.log('throttle triggered');
  }, 2000, [value]);

  return (
    <div onClick={() => setVal(value + 1)}>Just Test</div>
  );
};

export default RefreshPageButton;

after exploring the reason, I've found that because of the StrictMode, useThrottleFn will trigger as mount-unmount-mount in Next.js when first time rendering, which cause the timeoutCallback not triggered as expected and let the timeout ref value mistakenly remain exist.

Solution

import { useEffect, useRef, useState } from 'react';
import useUnmount from './useUnmount';

const useThrottleFn = <T, U extends any[]>(fn: (...args: U) => T, ms: number = 200, args: U) => {
  const [state, setState] = useState<T | null>(null);
  const timeout = useRef<ReturnType<typeof setTimeout>>();
  const nextArgs = useRef<U>();

  useEffect(() => {
    if (!timeout.current) {
      setState(fn(...args));
      const timeoutCallback = () => {
        if (nextArgs.current) {
          setState(fn(...nextArgs.current));
          nextArgs.current = undefined;
          timeout.current = setTimeout(timeoutCallback, ms);
        } else {
          timeout.current = undefined;
        }
      };
      timeout.current = setTimeout(timeoutCallback, ms);
    } else {
      nextArgs.current = args;
    }
  }, args);

  useUnmount(() => {
    timeout.current && clearTimeout(timeout.current);
    // reset timeout ref value to let `timeoutCallback` run as expected in StrictMode
    timeout.current = undefined;
  });

  return state;
};

export default useThrottleFn;

Type of change

  • [x] Bug fix useThrottle, useThrottleFn timeout ref value remain exist after first unmount in StrictMode.

Checklist

  • [x] Read the Contributing Guide
  • [x] Perform a code self-review
  • [x] Comment the code, particularly in hard-to-understand areas
  • [x] Add documentation
  • [x] Add hook's story at Storybook
  • [x] Cover changes with tests
  • [x] Ensure the test suite passes (yarn test)
  • [x] Provide 100% tests coverage
  • [x] Make sure code lints (yarn lint). Fix it with yarn lint:fix in case of failure.
  • [x] Make sure types are fine (yarn lint:types).

johnnywang1994 avatar Feb 08 '23 06:02 johnnywang1994

Looks like this fixes #2343 and #2488. Am curious why this hasn't been merged yet.

royvandewater avatar Apr 18 '24 17:04 royvandewater

Agreed. It would be awesome to have this merged 🙏🏼

royriver23 avatar Apr 24 '24 11:04 royriver23