Skip to content

useEffectOnlyOnceWhen

Runs a callback effect once when condition is met or is met in future

The useEffectOnlyOnceWhen hook is helpful when you want to run a callback effect atmost one time after a condition is met, after a component mounts.

The condition can be met at the beginning or in future re-renders.

useEffectOnlyOnceWhen

Loading...

Status: ⚒️

It should stop loading after 3 seconds.

Usage

Import the hook from @abhushanaj/react-hooks and use in required component;

./src/App.tsx
import { useEffectOnlyOnceWhen } from '@abhushanaj/react-hooks';
function App() {
const [shouldRun, setShouldRun] = React.useState(false);
useEffectOnlyOnceWhen(() => {
console.log('I am run');
}, shouldRun);
React.useEffect(() => {
let timerId = setTimeout(() => {
setShouldRun(true);
}, 2000);
return () => {
clearTimeout(timerId);
};
}, []);
return (
<div>
<p>I am now mounted!</p>
</div>
);
}
export default App;

API Reference

Parameters

ParameterTypeDescriptionDefault
callback()=>voidThe callback function to run after atmost onnce after the condition is met.N/A
conditionbooleanThe condition which needs to be met inorder for the effect callback to be invoked.N/A