DEV Community

Cover image for React Hook: useOnce
Slava Borodulin
Slava 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

Top comments (0)

Head over to your dashboard

See your total reactions, views, and listings.