All files / hooks/use-init/src useInit.ts

100% Statements 97/97
95.55% Branches 43/45
92.3% Functions 12/13
100% Lines 95/95

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356                                                                                                                                      3x 3x                                                                                                     112x   112x                         112x 112x 112x 112x 112x       112x 112x 112x 112x       112x 109x 109x 109x 109x 109x         112x 92x 92x 92x 8x 8x             112x   46x 3x     43x   43x   43x   43x           43x 43x 43x   43x 43x   43x 51x 1x     50x     50x     6x 6x 3x       6x   6x       5x 5x   4x 1x 1x                   5x 5x   3x 3x   5x 5x       1x 1x   1x     44x 44x 8x   24x         33x 9x 8x       1x 1x             33x 31x 31x             33x   16x     16x 8x           16x 8x                 42x       112x 7x 1x   6x           112x   112x 49x                       49x   49x   49x 40x     49x 49x 49x       112x              
import { useState, useEffect, useRef, useCallback } from "react";
 
/**
 * Options for useInit hook
 */
export interface UseInitOptions {
  /**
   * Only run initialization when this condition is true
   * @default true
   */
  when?: boolean;
  /**
   * Number of retry attempts on failure
   * @default 0
   */
  retry?: number;
  /**
   * Delay between retry attempts in milliseconds
   * @default 1000
   */
  retryDelay?: number;
  /**
   * Timeout for initialization in milliseconds
   * @default undefined (no timeout)
   */
  timeout?: number;
}
 
/**
 * Result object returned by useInit hook
 */
export interface UseInitResult {
  /**
   * Whether initialization has completed successfully
   */
  isInitialized: boolean;
  /**
   * Whether initialization is currently in progress
   */
  isInitializing: boolean;
  /**
   * Error that occurred during initialization, if any
   */
  error: Error | null;
  /**
   * Manually trigger re-initialization (respects `when` condition)
   */
  reinitialize: () => void;
}
 
/**
 * A function returned by an init callback that releases whatever the
 * initialization set up. Invoked on unmount and before re-initialization.
 */
export type CleanupFn = () => void;
 
/**
 * The initialization callback passed to {@link useInit}. It may be synchronous
 * or asynchronous and may optionally return a {@link CleanupFn}.
 */
export type InitCallback = () => void | CleanupFn | Promise<void | CleanupFn>;
 
/**
 * Custom error for timeout
 */
class InitTimeoutError extends Error {
  constructor(timeout: number) {
    super(`Initialization timed out after ${timeout}ms`);
    this.name = "InitTimeoutError";
  }
}
 
/**
 * A React hook for one-time initialization with async support, retry, timeout, and conditional execution.
 *
 * @param callback - The initialization function to run. Can be sync or async.
 *                   Can optionally return a cleanup function.
 * @param options - Configuration options for initialization
 * @returns Object containing initialization state and control functions
 *
 * @example
 * // Basic synchronous initialization
 * useInit(() => {
 *   console.log('Component initialized');
 * });
 *
 * @example
 * // With cleanup function
 * useInit(() => {
 *   const subscription = eventBus.subscribe();
 *   return () => subscription.unsubscribe();
 * });
 *
 * @example
 * // Async initialization with status tracking
 * const { isInitialized, isInitializing, error } = useInit(async () => {
 *   await loadConfiguration();
 * });
 *
 * @example
 * // Conditional initialization
 * useInit(() => {
 *   initializeAnalytics();
 * }, { when: isProduction });
 *
 * @example
 * // With retry and timeout
 * const { error, reinitialize } = useInit(async () => {
 *   await connectToServer();
 * }, {
 *   retry: 3,
 *   retryDelay: 1000,
 *   timeout: 5000
 * });
 */
export function useInit(
  callback: InitCallback,
  options: UseInitOptions = {}
): UseInitResult {
  const { when = true, retry = 0, retryDelay = 1000, timeout } = options;
 
  const [state, setState] = useState<{
    isInitialized: boolean;
    isInitializing: boolean;
    error: Error | null;
  }>({
    isInitialized: false,
    // Seed as pending when initialization is going to run, so the first commit
    // does not flash "not started" before the effect flips it to initializing.
    // `when` is a deterministic prop, so this stays SSR-safe.
    isInitializing: when,
    error: null,
  });
 
  const callbackRef = useRef<InitCallback>(callback);
  const cleanupRef = useRef<CleanupFn | null>(null);
  const hasInitializedRef = useRef(false);
  const mountedRef = useRef(true);
  const initializingRef = useRef(false);
 
  // Latest-value refs so `runInit` / `reinitialize` can stay identity-stable
  // (empty dependency arrays) while still reading the current props.
  const whenRef = useRef(when);
  const retryRef = useRef(retry);
  const retryDelayRef = useRef(retryDelay);
  const timeoutRef = useRef(timeout);
 
  // Concurrent-safe latest-ref pattern: mutate refs in an effect, never during
  // render. Runs on every commit so the values are always current.
  useEffect(() => {
    callbackRef.current = callback;
    whenRef.current = when;
    retryRef.current = retry;
    retryDelayRef.current = retryDelay;
    timeoutRef.current = timeout;
  });
 
  // Invoke the stored cleanup exactly once, swallowing any error so a throwing
  // cleanup can never wedge the hook or crash an unmount.
  const runCleanup = useCallback(() => {
    const cleanup = cleanupRef.current;
    cleanupRef.current = null;
    if (cleanup) {
      try {
        cleanup();
      } catch {
        // Intentionally swallow: a failed cleanup must not brick the hook.
      }
    }
  }, []);
 
  const runInit = useCallback(async () => {
    // Prevent concurrent initializations
    if (initializingRef.current) {
      return;
    }
 
    initializingRef.current = true;
 
    try {
      // Clean up previous initialization if any
      runCleanup();
 
      setState({
        isInitialized: false,
        isInitializing: true,
        error: null,
      });
 
      const retryCount = retryRef.current;
      const delay = retryDelayRef.current;
      const timeoutMs = timeoutRef.current;
 
      let lastError: Error | null = null;
      const maxAttempts = retryCount + 1;
 
      for (let attempt = 0; attempt < maxAttempts; attempt++) {
        if (!mountedRef.current) {
          return;
        }
 
        try {
          let result: void | CleanupFn;
 
          if (timeoutMs !== undefined) {
            // Race between callback and timeout
            let timeoutId: ReturnType<typeof setTimeout> | undefined;
            const timeoutPromise = new Promise<never>((_, reject) => {
              timeoutId = setTimeout(() => {
                reject(new InitTimeoutError(timeoutMs));
              }, timeoutMs);
            });
 
            const callbackResult = callbackRef.current();
 
            if (callbackResult instanceof Promise) {
              // If the callback loses the race but later resolves with a
              // cleanup function, that resource would otherwise be orphaned.
              // Release it as soon as it arrives.
              let abandoned = false;
              callbackResult
                .then((late) => {
                  if (abandoned && typeof late === "function") {
                    try {
                      (late as CleanupFn)();
                    } catch {
                      // Swallow: best-effort release of an orphaned resource.
                    }
                  }
                })
                .catch(() => {
                  // Swallow: the abandoned callback's own rejection is moot.
                });
 
              try {
                result = await Promise.race([callbackResult, timeoutPromise]);
              } catch (raceErr) {
                abandoned = true;
                throw raceErr;
              } finally {
                Eif (timeoutId !== undefined) {
                  clearTimeout(timeoutId);
                }
              }
            } else {
              Eif (timeoutId !== undefined) {
                clearTimeout(timeoutId);
              }
              result = callbackResult;
            }
          } else {
            const callbackResult = callbackRef.current();
            if (callbackResult instanceof Promise) {
              result = await callbackResult;
            } else {
              result = callbackResult;
            }
          }
 
          // Store cleanup function if returned
          if (typeof result === "function") {
            if (mountedRef.current) {
              cleanupRef.current = result as CleanupFn;
            } else {
              // Unmounted before completion: release immediately so the
              // resource is not leaked (the unmount cleanup already ran).
              try {
                (result as CleanupFn)();
              } catch {
                // Swallow: best-effort release.
              }
            }
          }
 
          if (mountedRef.current) {
            hasInitializedRef.current = true;
            setState({
              isInitialized: true,
              isInitializing: false,
              error: null,
            });
          }
 
          return;
        } catch (err) {
          lastError = err instanceof Error ? err : new Error(String(err));
 
          // If not the last attempt and still mounted, wait before retrying
          if (attempt < maxAttempts - 1 && mountedRef.current) {
            await new Promise((resolve) => setTimeout(resolve, delay));
          }
        }
      }
 
      // All attempts failed
      if (mountedRef.current) {
        setState({
          isInitialized: false,
          isInitializing: false,
          error: lastError,
        });
      }
    } finally {
      // Always release the concurrency latch, even if a cleanup or callback
      // threw synchronously, so the hook can never get permanently wedged.
      initializingRef.current = false;
    }
  }, [runCleanup]);
 
  const reinitialize = useCallback(() => {
    if (!whenRef.current) {
      return;
    }
    runInit();
  }, [runInit]);
 
  // `when` at the previous effect setup. Used to tell a genuine `when`
  // transition apart from a StrictMode-style teardown/re-setup with the same
  // `when` value.
  const prevWhenRef = useRef(when);
 
  useEffect(() => {
    mountedRef.current = true;
 
    // Run initialization if `when` is true AND either:
    // 1. We have never successfully initialized (first run / `when` first
    //    becomes true), OR
    // 2. This is a teardown/re-setup at the same `when` value (StrictMode's
    //    double-invoke, or any remount of this effect) — the previous cleanup
    //    tore the initialization down, so we must re-establish it. Because the
    //    effect only re-runs on a `when` change (runInit is identity-stable), an
    //    unchanged `when` at setup means the resource was just cleaned up and
    //    needs to be re-created, not a true→false→true intent change.
    const shouldInit =
      when && (!hasInitializedRef.current || prevWhenRef.current === when);
 
    prevWhenRef.current = when;
 
    if (shouldInit) {
      runInit();
    }
 
    return () => {
      mountedRef.current = false;
      runCleanup();
    };
  }, [when, runInit, runCleanup]);
 
  return {
    isInitialized: state.isInitialized,
    isInitializing: state.isInitializing,
    error: state.error,
    reinitialize,
  };
}