|
| 1 | +import React from "react"; |
| 2 | +import ActionButton from "../../commons/ActionButton"; |
| 3 | +import { useLog } from "../../commons/ExampleBloc"; |
| 4 | +import countPrimes from "./countPrimes"; |
| 5 | + |
| 6 | +const MyComponent = ({ |
| 7 | + values, |
| 8 | + label |
| 9 | +}: { |
| 10 | + values: number[]; |
| 11 | + label: string; |
| 12 | +}) => { |
| 13 | + const log = useLog(); |
| 14 | + |
| 15 | + const ref = React.useRef<{ previousValues: number[]; primes: number }>(); |
| 16 | + |
| 17 | + // Cache invalidation |
| 18 | + if (ref.current && ref.current.previousValues !== values) { |
| 19 | + ref.current = undefined; |
| 20 | + } |
| 21 | + |
| 22 | + // Cache computation |
| 23 | + if (!ref.current) { |
| 24 | + log("Before countPrimes"); |
| 25 | + const primes = countPrimes(values); |
| 26 | + log("After countPrimes"); |
| 27 | + ref.current = { |
| 28 | + // We need to track the previous parameters |
| 29 | + previousValues: values, |
| 30 | + primes |
| 31 | + }; |
| 32 | + } |
| 33 | + |
| 34 | + return ( |
| 35 | + <> |
| 36 | + Primes in {label}: {ref.current && ref.current.primes} |
| 37 | + </> |
| 38 | + ); |
| 39 | +}; |
| 40 | + |
| 41 | +const ExampleMemoization102 = () => { |
| 42 | + const log = useLog(); |
| 43 | + |
| 44 | + const [values, setValues] = React.useState<number[]>([]); |
| 45 | + const [label, setLabel] = React.useState<string>("my-label"); |
| 46 | + log("virtual-render", { valuesLength: values.length, label }); |
| 47 | + |
| 48 | + return ( |
| 49 | + <> |
| 50 | + <pre> |
| 51 | + {JSON.stringify({ valuesLength: values.length, label }, null, 2)} |
| 52 | + </pre> |
| 53 | + <div> |
| 54 | + <MyComponent values={values} label={label} /> |
| 55 | + </div> |
| 56 | + <ul> |
| 57 | + <li> |
| 58 | + <ActionButton |
| 59 | + label="Generate random values" |
| 60 | + onClick={() => { |
| 61 | + let values = []; |
| 62 | + for (let i = 0; i < 1000000; i++) { |
| 63 | + values.push(Math.floor(Math.random() * 1000000)); |
| 64 | + } |
| 65 | + setValues(values); |
| 66 | + }} |
| 67 | + /> |
| 68 | + </li> |
| 69 | + <li> |
| 70 | + <ActionButton |
| 71 | + label="Randomize label" |
| 72 | + onClick={() => { |
| 73 | + setLabel( |
| 74 | + Math.random() |
| 75 | + .toString(36) |
| 76 | + .substr(2, 5) |
| 77 | + ); |
| 78 | + }} |
| 79 | + /> |
| 80 | + </li> |
| 81 | + </ul> |
| 82 | + </> |
| 83 | + ); |
| 84 | +}; |
| 85 | + |
| 86 | +export default ExampleMemoization102; |
0 commit comments