Skip to content
usefy

useInit

Lifecycle & refs

A powerful React hook for one-time initialization with async support, retry, timeout, and conditional execution

Install

$ npm install @usefy/use-init

Quick 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

ParameterTypeDefaultDescription
callbackInitCallbackThe initialization function to run
optionsUseInitOptions{}Configuration options for initialization

Callback Type

The callback can be:

  • Synchronous: () => void
  • Asynchronous: () => Promise<void>
  • With cleanup: () => void | CleanupFn or () => Promise<void | CleanupFn>

Where CleanupFn is () => void - a function that will be called when the component unmounts or before re-initialization.

Options

OptionTypeDefaultDescription
whenbooleantrueOnly run initialization when this condition is true
retrynumber0Number of retry attempts on failure
retryDelaynumber1000Delay between retry attempts in milliseconds
timeoutnumberTimeout for initialization in milliseconds

Returns UseInitResult

PropertyTypeDescription
isInitializedbooleanWhether initialization has completed successfully
isInitializingbooleanWhether initialization is currently in progress
errorError | nullError that occurred during initialization, if any
reinitialize() => voidManually 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.

More in lifecycle & refs