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 | 2x 2x 76x 76x 76x 76x 76x 76x 76x 76x 76x 29x 29x 29x 1x 1x 29x 29x 29x 29x 36x 36x 36x 5x 5x 2x 5x 5x 4x 4x 4x 4x 1x 1x 1x 31x 31x 4x 16x 22x 3x 22x 21x 21x 22x 22x 14x 14x 7x 14x 7x 7x 76x 3x 1x 2x 76x 76x 76x 33x 33x 33x 33x 33x 27x 27x 33x 33x 33x 2x 2x 76x | 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;
}
/**
* Type for cleanup function returned by init callback
*/
type CleanupFn = () => void;
/**
* Type for init callback function
*/
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,
isInitializing: false,
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);
// Always update callback ref to latest version
callbackRef.current = callback;
const runInit = useCallback(async () => {
// Prevent concurrent initializations
Iif (initializingRef.current) {
return;
}
initializingRef.current = true;
// Clean up previous initialization if any
if (cleanupRef.current) {
cleanupRef.current();
cleanupRef.current = null;
}
setState({
isInitialized: false,
isInitializing: true,
error: null,
});
let lastError: Error | null = null;
const maxAttempts = retry + 1;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
Iif (!mountedRef.current) {
initializingRef.current = false;
return;
}
try {
let result: void | CleanupFn;
if (timeout !== undefined) {
// Race between callback and timeout
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => {
reject(new InitTimeoutError(timeout));
}, timeout);
});
const callbackResult = callbackRef.current();
if (callbackResult instanceof Promise) {
try {
result = await Promise.race([callbackResult, timeoutPromise]);
} 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") {
cleanupRef.current = result;
}
if (mountedRef.current) {
hasInitializedRef.current = true;
setState({
isInitialized: true,
isInitializing: false,
error: null,
});
}
initializingRef.current = false;
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, retryDelay));
}
}
}
// All attempts failed
if (mountedRef.current) {
setState({
isInitialized: false,
isInitializing: false,
error: lastError,
});
}
initializingRef.current = false;
}, [retry, retryDelay, timeout]);
const reinitialize = useCallback(() => {
if (!when) {
return;
}
runInit();
}, [when, runInit]);
// Track when condition changes from false to true
const prevWhenRef = useRef(when);
const hasRunOnceRef = useRef(false);
useEffect(() => {
mountedRef.current = true;
// Run initialization if:
// 1. `when` is true AND
// 2. Never successfully initialized AND
// 3. Either first run OR `when` just changed from false to true
const whenJustBecameTrue = !prevWhenRef.current && when;
const shouldInit =
when &&
!hasInitializedRef.current &&
(!hasRunOnceRef.current || whenJustBecameTrue);
prevWhenRef.current = when;
if (shouldInit) {
hasRunOnceRef.current = true;
runInit();
}
return () => {
mountedRef.current = false;
if (cleanupRef.current) {
cleanupRef.current();
cleanupRef.current = null;
}
};
}, [when, runInit]);
return {
isInitialized: state.isInitialized,
isInitializing: state.isInitializing,
error: state.error,
reinitialize,
};
}
|