Skip to content

Instantly share code, notes, and snippets.

@arminyahya
Created July 5, 2019 03:45
Show Gist options
  • Save arminyahya/9ddeb23899baf09f2ea581f38c7a4bef to your computer and use it in GitHub Desktop.
Save arminyahya/9ddeb23899baf09f2ea581f38c7a4bef to your computer and use it in GitHub Desktop.
useInstance hook
import { useRef } from 'react';
export const useInstance = <T>(fn: () => T) => {
const instanceRef = useRef<T | null>(null);
if (instanceRef.current === null) {
instanceRef.current = fn();
}
return instanceRef.current as T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment