Skip to content

Instantly share code, notes, and snippets.

@40detectives
Last active March 26, 2022 15:38
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 40detectives/74beef988babbe99c9314fdcdaa4a6e9 to your computer and use it in GitHub Desktop.
Save 40detectives/74beef988babbe99c9314fdcdaa4a6e9 to your computer and use it in GitHub Desktop.
useMemo hook with a real memoization storage (using recursive fibonacci)
// This is an example of Reacts's useMemo hook,
// useMemo only really does a "render memoization" for react internally, i.e.: skipping calculation in some renders.
// in this example I try to circumvent that and make useMemo to also cache previous calls in an object.
// ALSO: the ideal way of doing this for fibonacci would be doing the memoization in the fibonacci function itself,
// that way you could remember all the n-1 fibonacci numbers after just one fibonacci(n) call.
import { useState, useMemo } from "react";
const fibonacci = (n) => {
if (n < 0) return NaN;
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
};
const RealMemoizationComponent = () => {
const [num, setNum] = useState(0);
const [memoizedFibs, setMemoizedFibs] = useState({}); // initial state is an empty obj
const [isGreen, setIsGreen] = useState(true);
const fib = useMemo(() => {
const key = num < 0 ? NaN : num;
const exist = memoizedFibs[key];
if (exist !== undefined) return exist;
const newFib = fibonacci(num);
setMemoizedFibs({
...memoizedFibs,
[num < 0 ? NaN : num]: newFib
});
}, [num, memoizedFibs]);
// you can inspect the cache at this point:
// console.log(memoizedFibs);
return (
<div>
<h1
onClick={() => setIsGreen(!isGreen)}
style={{ color: isGreen ? "limegreen" : "crimson" }}
>
useMemo Example
</h1>
<h2>
Fibonacci of {num} is {fib}
</h2>
<button onClick={() => setNum(num - 1)}>➖</button>
<button onClick={() => setNum(num + 1)}>➕</button>
</div>
);
};
export default MemoComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment