Skip to content

useCallbackOncePerRender ​

useCallbackOncePerRender is a React hook that ensures a callback function is executed only once, regardless of how many times it's called. This is useful for one-time operations that should not be repeated, even if the component re-renders.

Interface ​

ts
function useCallbackOncePerRender<F extends (...args: any[]) => void>(
  callback: () => void,
  deps: DependencyList
): (...args: any[]) => void;

Parameters ​

  • callbackrequired · () => void

    The callback function to be executed once.

  • depsrequired · DependencyList

    Dependencies array that will trigger a new one-time execution when changed.

Return Value ​

  • (...args: any[]) => void

    A memoized function that will only execute once until dependencies change.

Example ​

tsx
import { useCallbackOncePerRender } from 'react-simplikit';

function Component() {
  const handleOneTimeEvent = useCallbackOncePerRender(() => {
    console.log('This will only run once');
  }, []);

  return <button onClick={handleOneTimeEvent}>Click me</button>;
}
tsx
// With dependencies
function TrackingComponent({ userId }: { userId: string }) {
  const trackUserVisit = useCallbackOncePerRender(() => {
    analytics.trackVisit(userId);
  }, [userId]);

  useEffect(() => {
    trackUserVisit();
  }, [trackUserVisit]);

  return <div>User page</div>;
}

Released under the MIT License.