Created
November 18, 2019 20:41
-
-
Save jtmthf/8f33bd382a091a59755450a5146b0225 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, 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