Skip to content

Instantly share code, notes, and snippets.

@tjinlag
Last active July 8, 2021 05:25
Show Gist options
  • Save tjinlag/ba3d1bf0191c77648a4abcc60064b23e to your computer and use it in GitHub Desktop.
Save tjinlag/ba3d1bf0191c77648a4abcc60064b23e to your computer and use it in GitHub Desktop.
React.memo() with function in props
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