Last active
September 19, 2019 05:31
-
-
Save ryanflorence/58899db72d0541eff1dd5c3c999c8fdc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function App() { | |
// updates App every 100ms | |
const now = useStopWatch(100) | |
// this is a new function every time | |
const handleModelSelect = vehicle => { | |
console.log(vehicle) | |
} | |
return ( | |
<div> | |
<h1>{now}</h1> | |
<VehicleModels onModelSelect={handleModelSelect} /> | |
</div> | |
) | |
} | |
function VehicleModels({ onItemSelect }) { | |
// we memoized this because `Sedan` is `memo`d | |
// but it depends on `onItemSelect`, which is new every time | |
const handleSedanSelect = useMemo(() => { | |
onItemSelect('sedan') | |
}, [onItemSelect]) | |
const handleTruckSelect = () => { | |
doSomethingTruckSpecific() | |
onItemSelect('truck') | |
} | |
return ( | |
<div> | |
<Sedan onSelect={handleSedanSelect}/> | |
<Truck onSelect={handleTruckSelect}/> | |
</div> | |
) | |
} | |
const Sedan = React.memo(({ onSelect }) => { }) | |
// 1. if we React.memo Sedan | |
// 2. and only useMemo `handleSedanSelect` (and not App `handleModelSelect`) | |
// 3. App `now` updates | |
// 4. `handleModelSelect` is a new function | |
// 5. therefore `VehicleModels` `props.onItemSelect` is new | |
// 6. therefore VehicleModels `handleSedanSelect` `useMemo` will make a new function | |
// 7. therefore Sedan's React.memo didn't do anything. | |
// 8. therefore we need to `useMemo` all the way up the tree | |
// even if we didn't `React.memo` all the way up the tree |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have also experienced this issue a lot so I made this: https://gist.github.com/ricokahler/d88693d00b0660e7639ee8bc225390b1
It's
React.memo
but it ignores function changes while also keeping the functions up-to-date.btw I'm not recommending anyone use this thing all the time (e.g. premature optimization is the root of all evil etc) but if you do need to memoize part of your tree, this may save you from using memo +
useCallback
"all the way up the tree"