useMemoWithPrevious.ts 664 B

12345678910111213141516171819202122
  1. import {useState} from 'react';
  2. import {useEffectAfterFirstRender} from './useEffectAfterFirstRender';
  3. import usePrevious from './usePrevious';
  4. const useMemoWithPrevious = <T>(
  5. factory: (previousInstance: T | null) => T,
  6. deps: React.DependencyList
  7. ): T => {
  8. const [value, setValue] = useState<T>(() => factory(null));
  9. const previous = usePrevious<T | null>(value);
  10. useEffectAfterFirstRender(() => {
  11. setValue(factory(previous));
  12. // Dependencies are explicitly managed and the deps warning is enabled for the custom hook.
  13. // eslint-disable-next-line react-hooks/exhaustive-deps
  14. }, deps);
  15. return value;
  16. };
  17. export {useMemoWithPrevious};