Skip to content

Instantly share code, notes, and snippets.

@theer1k
Last active September 22, 2022 12:19
Show Gist options
  • Save theer1k/4ae187a4856dd14557c372ef59ceb3c5 to your computer and use it in GitHub Desktop.
Save theer1k/4ae187a4856dd14557c372ef59ceb3c5 to your computer and use it in GitHub Desktop.
useRunOnce
import React, { useEffect, useRef } from "react";
export type useRunOnceProps = {
fn: () => any;
sessionKey?: string;
};
const useRunOnce: React.FC<useRunOnceProps> = ({ fn, sessionKey }) => {
const triggered = useRef<boolean>(false);
useEffect(() => {
const hasBeenTriggered = sessionKey
? sessionStorage.getItem(sessionKey)
: triggered.current;
if (!hasBeenTriggered) {
fn();
triggered.current = true;
if (sessionKey) {
sessionStorage.setItem(sessionKey, "true");
}
}
}, [fn, sessionKey]);
return null;
};
export default useRunOnce;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment