From 0c45eb69dc071e3634086a221149c953315b0be0 Mon Sep 17 00:00:00 2001 From: Rafi Arrafif Date: Mon, 1 Sep 2025 19:29:30 +0700 Subject: [PATCH] :bulb: (docs) add documentation for runOnce hook --- shared/hooks/useRunOnce.ts | 40 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/shared/hooks/useRunOnce.ts b/shared/hooks/useRunOnce.ts index 98fe4ca..f7dbea5 100644 --- a/shared/hooks/useRunOnce.ts +++ b/shared/hooks/useRunOnce.ts @@ -1,6 +1,46 @@ "use client"; import { useEffect, useRef } from "react"; +/** + * @function useRunOnce + * @description A custom React hook that ensures a function is executed only once + * across the entire application, even in React Strict Mode or during + * development hot reloads. Maintains a global registry to track + * execution status using a unique key. + * + * Particularly useful for one-time initialization logic, analytics + * tracking, or any operation that should not be duplicated. + * + * @param {string} key - A unique identifier for the process. Used to track execution + * across component instances and prevent naming collisions. + * Should be descriptive and unique (e.g., "user_analytics_init"). + * @param {function} fn - The function to be executed once. Should contain the logic + * that needs to run only a single time. + * + * @returns {void} + * + * @throws {Error} If the provided key is not a string or is empty. + * @throws {Error} If the provided function is not callable. + * + * @example + * // One-time asynchronous operation + * useRunOnce("async_operation", async () => { + * await yourAsyncFunction(); + * }); + * + * @example + * // One-time synchronous operation + * useRunOnce("sync_operation", () => { + * yourFunction(); + * }); + * + * @remarks + * - The hook uses a global registry, so the same key across different components + * will prevent duplicate execution. + * - Safe to use in React Strict Mode and development environment with hot reload. + * - The function will not execute if another instance with the same key has + * already run in the application. + */ const registry = new Set(); export function useRunOnce(key: string, fn: () => void) {