Skip to content

Instantly share code, notes, and snippets.

@honungsburk
Last active June 2, 2022 09:09
Show Gist options
  • Save honungsburk/b15b18ca2087affd2361fc01122c4ac8 to your computer and use it in GitHub Desktop.
Save honungsburk/b15b18ca2087affd2361fc01122c4ac8 to your computer and use it in GitHub Desktop.
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