Skip to main content

useCallbackOnce

A custom hook that ensures the given callback function is executed only once and never again after the first call.


Code

🔗 View source code


Interface

typescript
function useCallbackOnce<F extends (...args: any[]) => void>(callback: F): F

Parameters

NameTypeDescription
callbackFThe callback function to be executed only once

Usage

typescript
import { useCallbackOnce } from '@modern-kit/react';
import { useState } from 'react';

export const Example = () => {
const [value, setValue] = useState(0);

const handleClick = useCallbackOnce((e) => {
alert('Runs only once!')
});

return (
<div>
<p>Current state: {value}</p>
<button onClick={handleClick}>Call CallbackOnce</button>
<button onClick={() => setValue(value + 1)}>Re-render via state change</button>
</div>
);
};

Example

Current state: 0