DEV Community

Cover image for React Hook: useOnce
Viacheslav Borodulin
Viacheslav Borodulin

Posted on

React Hook: useOnce

import { useEffect, useRef } from 'react';

const useOnce = (
  cond: () => boolean,
  cb: () => void,
  deps: any[]
) => {
  const didCallRef = useRef<boolean>(false);

  useEffect(() => {
    if (didCallRef.current || !cond()) {
      return;
    }

    didCallRef.current = true;
    cb();
  }, [deps]);
};

export {
  useOnce,
};
Enter fullscreen mode Exit fullscreen mode

Usage example:

useOnce(
    () => bookingTime && bookingTime !== 'UNSET',
    () => logEvent('select time'),
    [ bookingTime ]
  );
Enter fullscreen mode Exit fullscreen mode

Discussion (0)