Created
September 17, 2019 08:20
-
-
Save smashingpat/93465c75a18181b0c9c8c5bca7c7ea67 to your computer and use it in GitHub Desktop.
use-inline-memo
This file contains 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 * as React from 'react'; | |
import useInlineMemo from './useInlineMemo'; | |
function App() { | |
const [value, setValue] = React.useState(""); | |
const memo = useInlineMemo(); | |
return ( | |
<input | |
type="text" | |
value={value} | |
onChange={memo("change", ev => setValue(ev.target.value))} | |
/> | |
); | |
} |
This file contains 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
export default function useInlineMemo() { | |
const cache = React.useMemo(() => new Map<string, any>(), []); | |
return function memo<T>(key: string, value: T): T { | |
if (!cache.has(key)) { | |
cache.set(key, value); | |
} | |
return cache.get(key); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment