|
| 1 | + |
| 2 | +## Input |
| 3 | + |
| 4 | +```javascript |
| 5 | +import { useEffect } from "react"; |
| 6 | +import { useIdentity } from "shared-runtime"; |
| 7 | + |
| 8 | +function Component() { |
| 9 | + let local; |
| 10 | + |
| 11 | + const reassignLocal = (newValue) => { |
| 12 | + local = newValue; |
| 13 | + }; |
| 14 | + |
| 15 | + const callback = (newValue) => { |
| 16 | + reassignLocal("hello"); |
| 17 | + |
| 18 | + if (local === newValue) { |
| 19 | + // Without React Compiler, `reassignLocal` is freshly created |
| 20 | + // on each render, capturing a binding to the latest `local`, |
| 21 | + // such that invoking reassignLocal will reassign the same |
| 22 | + // binding that we are observing in the if condition, and |
| 23 | + // we reach this branch |
| 24 | + console.log("`local` was updated!"); |
| 25 | + } else { |
| 26 | + // With React Compiler enabled, `reassignLocal` is only created |
| 27 | + // once, capturing a binding to `local` in that render pass. |
| 28 | + // Therefore, calling `reassignLocal` will reassign the wrong |
| 29 | + // version of `local`, and not update the binding we are checking |
| 30 | + // in the if condition. |
| 31 | + // |
| 32 | + // To protect against this, we disallow reassigning locals from |
| 33 | + // functions that escape |
| 34 | + throw new Error("`local` not updated!"); |
| 35 | + } |
| 36 | + }; |
| 37 | + |
| 38 | + useIdentity(() => { |
| 39 | + callback(); |
| 40 | + }); |
| 41 | + |
| 42 | + return "ok"; |
| 43 | +} |
| 44 | + |
| 45 | +``` |
| 46 | + |
| 47 | +## Code |
| 48 | + |
| 49 | +```javascript |
| 50 | +import { c as _c } from "react/compiler-runtime"; |
| 51 | +import { useEffect } from "react"; |
| 52 | +import { useIdentity } from "shared-runtime"; |
| 53 | + |
| 54 | +function Component() { |
| 55 | + const $ = _c(3); |
| 56 | + let local; |
| 57 | + let t0; |
| 58 | + if ($[0] === Symbol.for("react.memo_cache_sentinel")) { |
| 59 | + t0 = (newValue) => { |
| 60 | + local = newValue; |
| 61 | + }; |
| 62 | + $[0] = t0; |
| 63 | + } else { |
| 64 | + t0 = $[0]; |
| 65 | + } |
| 66 | + const reassignLocal = t0; |
| 67 | + let t1; |
| 68 | + if ($[1] === Symbol.for("react.memo_cache_sentinel")) { |
| 69 | + t1 = (newValue_0) => { |
| 70 | + reassignLocal("hello"); |
| 71 | + if (local === newValue_0) { |
| 72 | + console.log("`local` was updated!"); |
| 73 | + } else { |
| 74 | + throw new Error("`local` not updated!"); |
| 75 | + } |
| 76 | + }; |
| 77 | + $[1] = t1; |
| 78 | + } else { |
| 79 | + t1 = $[1]; |
| 80 | + } |
| 81 | + const callback = t1; |
| 82 | + let t2; |
| 83 | + if ($[2] === Symbol.for("react.memo_cache_sentinel")) { |
| 84 | + t2 = () => { |
| 85 | + callback(); |
| 86 | + }; |
| 87 | + $[2] = t2; |
| 88 | + } else { |
| 89 | + t2 = $[2]; |
| 90 | + } |
| 91 | + useIdentity(t2); |
| 92 | + return "ok"; |
| 93 | +} |
| 94 | + |
| 95 | +``` |
| 96 | + |
0 commit comments