Last active
July 8, 2021 05:25
-
-
Save tjinlag/ba3d1bf0191c77648a4abcc60064b23e to your computer and use it in GitHub Desktop.
React.memo() with function in props
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
const MemoizedComponent = React.memo(MyComponent); | |
// In this case, the MemoizedComponent will re-render when the App re-render. | |
// Because when the app re-render, the function handleClick will have the new reference. | |
const App = () => { | |
const handleClick = () => { | |
// logic when click ... | |
} | |
return ( | |
<MemoizedComponent onClick={handleClick} /> | |
) | |
} | |
// We resolve the above case with useCallback. It only create new function when the dependencies changed | |
const App = () => { | |
const handleClick = useCallback(() => { | |
// logic when click ... | |
}, dependencies) // this line only run (re-assign new reference into function handleClick) if the dependencies is changed | |
return ( | |
<MemoizedComponent onClick={handleClick} /> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment