Skip to content

Instantly share code, notes, and snippets.

@imsarvesh
Last active March 29, 2020 20:09
Show Gist options
  • Save imsarvesh/a7a3b2c207845f14c3f47dc92657734f to your computer and use it in GitHub Desktop.
Save imsarvesh/a7a3b2c207845f14c3f47dc92657734f to your computer and use it in GitHub Desktop.
useMemo Example
import { useState, useMemo } from 'react';
// Usage
function App() {
const [count, setCount] = useState(0);
const [wordIndex, setWordIndex] = useState(0);
const words = ['hey', 'this', 'is', 'cool'];
const word = words[wordIndex];
const computeLetterCount = word => {
let i = 0;
while (i < 1000000000) i++;
return word.length;
};
const letterCount = useMemo(() => computeLetterCount(word), [word]);
return (
<div style={{ padding: '15px' }}>
<h2>Compute number of letters (slow 🐌)</h2>
<p>"{word}" has {letterCount} letters</p>
<button
onClick={() => {
const next = wordIndex + 1 === words.length ? 0 : wordIndex + 1;
setWordIndex(next);
}}
>
Next word
</button>
<h2>Increment a counter (fast ⚡️)</h2>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
ReactDOM.render(<App/>, mountNode);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment