useMemoWithPrevious.ts 508 B

1234567891011121314151617181920
  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. }, deps);
  13. return value;
  14. };
  15. export {useMemoWithPrevious};