DEV Community

loading...
Cover image for React Hook: useOnce

React Hook: useOnce

Viacheslav Borodulin
Software engineer, CEO at https://chpokify.com
・1 min read
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)