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.
19 lines
354 B
TypeScript
19 lines
354 B
TypeScript
"use client";
|
|
import { useEffect, useRef } from "react";
|
|
|
|
const registry = new Set<string>();
|
|
|
|
export function useRunOnce(key: string, fn: () => void) {
|
|
const hasRun = useRef(false);
|
|
|
|
useEffect(() => {
|
|
if (hasRun.current) return;
|
|
hasRun.current = true;
|
|
|
|
if (registry.has(key)) return;
|
|
registry.add(key);
|
|
|
|
fn();
|
|
}, [key, fn]);
|
|
}
|