Last active
September 22, 2022 12:19
-
-
Save theer1k/4ae187a4856dd14557c372ef59ceb3c5 to your computer and use it in GitHub Desktop.
useRunOnce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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