🚩 (flags) create run once hooks
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.
This commit is contained in:
0
shared/hooks/useRunOnce.debug.ts
Normal file
0
shared/hooks/useRunOnce.debug.ts
Normal file
@ -1,36 +1,18 @@
|
|||||||
|
"use client";
|
||||||
import { useEffect, useRef } from "react";
|
import { useEffect, useRef } from "react";
|
||||||
|
|
||||||
/**
|
const registry = new Set<string>();
|
||||||
* @module useRunOnce
|
|
||||||
* @description A custom React hook that ensures a callback function is executed only once
|
export function useRunOnce(key: string, fn: () => void) {
|
||||||
* during the component's lifecycle, even in React Strict Mode or development with hot reloading.
|
const hasRun = useRef(false);
|
||||||
*
|
|
||||||
* @param {() => void | Promise<void>} callback - The function to execute once. Can be synchronous or asynchronous.
|
|
||||||
* @returns {void}
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* // Synchronous usage
|
|
||||||
* useRunOnce(() => {
|
|
||||||
* console.log('This runs only once');
|
|
||||||
* initializeSomething();
|
|
||||||
* });
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* // Asynchronous usage
|
|
||||||
* useRunOnce(async () => {
|
|
||||||
* const data = await fetchData();
|
|
||||||
* setInitialData(data);
|
|
||||||
* });
|
|
||||||
*/
|
|
||||||
const useRunOnce = (callback: () => void | Promise<void>) => {
|
|
||||||
const calledRef = useRef(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (calledRef.current) return;
|
if (hasRun.current) return;
|
||||||
calledRef.current = true;
|
hasRun.current = true;
|
||||||
|
|
||||||
void callback();
|
if (registry.has(key)) return;
|
||||||
}, [callback]);
|
registry.add(key);
|
||||||
};
|
|
||||||
|
|
||||||
export default useRunOnce;
|
fn();
|
||||||
|
}, [key, fn]);
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user