useInit
Lifecycle & refsA powerful React hook for one-time initialization with async support, retry, timeout, and conditional execution
Install
$ npm install @usefy/use-initQuick start
useInit.tsx
import { useInit } from "@usefy/use-init";
function MyComponent() {
const { isInitialized, isInitializing, error } = useInit(async () => {
await loadConfiguration();
console.log("Component initialized!");
});
if (isInitializing) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (!isInitialized) return null;
return <div>Ready!</div>;
}API reference
useInit(callback, options?)
A hook that executes initialization logic exactly once when the component mounts (or when conditions are met).
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
callback | InitCallback | — | The initialization function to run |
options | UseInitOptions | {} | Configuration options for initialization |
Callback Type
The callback can be:
- Synchronous:
() => void - Asynchronous:
() => Promise<void> - With cleanup:
() => void | CleanupFnor() => Promise<void | CleanupFn>
Where CleanupFn is () => void - a function that will be called when the component unmounts or before re-initialization.
Options
| Option | Type | Default | Description |
|---|---|---|---|
when | boolean | true | Only run initialization when this condition is true |
retry | number | 0 | Number of retry attempts on failure |
retryDelay | number | 1000 | Delay between retry attempts in milliseconds |
timeout | number | — | Timeout for initialization in milliseconds |
Returns UseInitResult
| Property | Type | Description |
|---|---|---|
isInitialized | boolean | Whether initialization has completed successfully |
isInitializing | boolean | Whether initialization is currently in progress |
error | Error | null | Error that occurred during initialization, if any |
reinitialize | () => void | Manually trigger re-initialization (respects when condition) |
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.