Skip to main content

useOnceEffect

A custom hook that runs only once when the component mounts.

It behaves the same as passing an empty dependency array ([]) to useEffect, but makes the intent explicit.


Code

🔗 View source code


Interface

typescript
function useOnceEffect(effectCallback: EffectCallback): void

Parameters

NameTypeDescription
effectCallbackEffectCallbackEffect function to run once on mount

Usage

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

const Example = () => {
const [count, setCount] = useState(0);

useOnceEffect(() => {
console.log('Component has mounted.');
});

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};

Example

Count: 0

Even after re-rendering by changing state, the effect is called only once.