Last active
June 2, 2022 09:09
-
-
Save honungsburk/b15b18ca2087affd2361fc01122c4ac8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 { useEffect, useRef } from "react"; | |
/** | |
* Only want to un the init code once? useRefOnce to the rescue! | |
* | |
* @param init the function that produces the inital value | |
* @returns | |
*/ | |
export default function useRefOnce<V>( | |
init: () => V | |
): React.MutableRefObject<V | undefined> { | |
const ref = useRef<V | undefined>(undefined); | |
useEffect(() => { | |
if (!ref.current) { | |
ref.current = init(); | |
} | |
},[]); | |
return ref; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment