Skip to content

Instantly share code, notes, and snippets.

@jtmthf
Created November 18, 2019 20:41
Show Gist options
  • Select an option

  • Save jtmthf/8f33bd382a091a59755450a5146b0225 to your computer and use it in GitHub Desktop.

Select an option

Save jtmthf/8f33bd382a091a59755450a5146b0225 to your computer and use it in GitHub Desktop.
import { useEffect, useState, useCallback, DependencyList } from 'react';
function useLazy<T>(factory: () => T, deps: DependencyList | undefined): () => T {
const [state, setState] = useState<{ used: false } | { used: true; value: T }>({ used: false });
useEffect(() => {
setState({ used: false })
}, deps);
return useCallback(() => {
if (state.used) {
return state.value;
}
const newValue = factory();
setState({ used: true, value: newValue });
return newValue;
}, [state])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment