usePrevious.tsx 1.0 KB

1234567891011121314151617181920212223
  1. import {useEffect, useRef} from 'react';
  2. /**
  3. * Provides previous prop or state inside of function components.
  4. * It’s possible that in the future React will provide a usePrevious Hook out of the box since it’s a relatively common use case.
  5. * @see {@link https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state}
  6. *
  7. * @returns 'ref.current' and therefore should not be used as a dependency of useEffect.
  8. * Mutable values like 'ref.current' are not valid dependencies of useEffect because changing them does not re-render the component.
  9. */
  10. function usePrevious<T>(value: T): T {
  11. // The ref object is a generic container whose current property is mutable ...
  12. // ... and can hold any value, similar to an instance property on a class
  13. const ref = useRef<T>(value);
  14. // Store current value in ref
  15. useEffect(() => {
  16. ref.current = value;
  17. }, [value]); // Only re-run if value changes
  18. // Return previous value (happens before update in useEffect above)
  19. return ref.current;
  20. }
  21. export default usePrevious;