useCleanup.ts 609 B

12345678910111213141516
  1. import { useEffect, useRef } from 'react';
  2. import { useDispatch } from 'react-redux';
  3. import { cleanUpAction, StateSelector } from '../actions/cleanUp';
  4. export function useCleanup<T>(stateSelector: StateSelector<T>) {
  5. const dispatch = useDispatch();
  6. //bit of a hack to unburden user from having to wrap stateSelcetor in a useCallback. Otherwise cleanup would happen on every render
  7. const selectorRef = useRef(stateSelector);
  8. selectorRef.current = stateSelector;
  9. useEffect(() => {
  10. return () => {
  11. dispatch(cleanUpAction({ stateSelector: selectorRef.current }));
  12. };
  13. }, [dispatch]);
  14. }