useEffectOnceWhen
Runs the latest callback once when a condition first becomes true.
About
useEffectOnceWhen waits for a condition and invokes a callback at most once for the current mounted hook instance. It is useful for one-time initialization that cannot begin until data or consent becomes available.
Examples
import { useState } from "react";
import { useEffectOnceWhen } from "rooks";
export default function OneTimeWelcome() {
const [ready, setReady] = useState(false);
const [message, setMessage] = useState("Waiting");
useEffectOnceWhen(() => setMessage("Welcome initialized"), ready);
return (
<section>
<p role="status">{message}</p>
<button type="button" onClick={() => setReady(true)}>
Become ready
</button>
</section>
);
}Parameters
| Argument | Type | Default | Meaning |
|---|---|---|---|
callback | () => void | required | Latest callback to run once. |
when | boolean | true | Enables the one-time invocation. |
Return value
The hook returns void; callback return values are ignored.
Behavior and lifecycle
One effect refreshes the callback after every commit, and another watches when. The first committed true invokes the current callback and permanently marks this hook instance as complete. Returning when to false and then true does not run it again. A full unmount and remount creates a new instance.
Compatibility and accessibility
No browser API is required, and effects do not run during server rendering. If the one-time action depends on permission or user intent, trigger the condition from an explicit accessible control rather than mount alone.