Last active
October 15, 2020 08:12
-
-
Save donaldpipowitch/356f1f6e58d805cfd22c673f909a7083 to your computer and use it in GitHub Desktop.
useStableMemo
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 { DependencyList, useState, useEffect, useRef } from 'react'; | |
| // use this instead of useMemo of you need a stable value | |
| // see https://twitter.com/0xca0a/status/1314326386555924480 | |
| export function useStableMemo<T>(factory: () => T, deps: DependencyList): T { | |
| const [value, setValue] = useState<T>(factory); | |
| const firstRun = useRef(true); | |
| useEffect( | |
| () => { | |
| if (firstRun.current) { | |
| firstRun.current = false; | |
| } else { | |
| setValue(factory); | |
| } | |
| }, | |
| // eslint-disable-next-line react-hooks/exhaustive-deps | |
| deps | |
| ); | |
| return value; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment