Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { useState, useMemo } from 'react';
// Usage
function App() {
// State for our counter
const [count, setCount] = useState(0);
// State to keep track of current word in array we want to show
const [wordIndex, setWordIndex] = useState(0);
// Words we can flip through and view letter count
const words = ['hey', 'this', 'is', 'cool'];
const word = words[wordIndex];
// Returns number of letters in a word
// We make it slow by including a large and completely unnecessary loop
const computeLetterCount = word => {
let i = 0;
while (i < 1000000000) i++;
return word.length;
};
// Memoize computeLetterCount so it uses cached return value if input array ...
// ... values are the same as last time the function was run.
const letterCount = useMemo(() => computeLetterCount(word), [word]);
// This would result in lag when incrementing the counter because ...
// ... we'd have to wait for expensive function when re-rendering.
//const letterCount = computeLetterCount(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>
);
}
@danielsdesk

This comment has been minimized.

Copy link

@danielsdesk danielsdesk commented Jun 11, 2020

FYI looks like this example errors in codesandbox due to infinite loop

@vinayakshahdeo

This comment has been minimized.

Copy link

@vinayakshahdeo vinayakshahdeo commented Aug 24, 2020

Yes a big infinite loop is the problem

@gragland

This comment has been minimized.

Copy link
Owner Author

@gragland gragland commented Sep 9, 2020

@danielsdesk @vinayakshahdeo Thanks for letting me know. It wasn't actually an infinite loop, but Codesandbox didn't like the intentional 1,000,000,000 iterations in the computeLetterCount function. I was able to disable infinite loop protection so that the Codesandbox runs now :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.