Skip to content

Instantly share code, notes, and snippets.

@smashingpat
Created September 17, 2019 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smashingpat/93465c75a18181b0c9c8c5bca7c7ea67 to your computer and use it in GitHub Desktop.
Save smashingpat/93465c75a18181b0c9c8c5bca7c7ea67 to your computer and use it in GitHub Desktop.
use-inline-memo
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))}
/>
);
}
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