I'm reading about hooks in React, and I have some trouble understanding the difference between useRef and useCallback hooks.
Specifically, I'm looking to understand how these two can be used to avoid unnecessary re-renders of child components.
Based on my understanding of this answer on stack overflow, the following function can be written as:
const Avatar = function({ history, url, fullName }) {
const onMenuItemClick = urlToNavigate => history.push(urlToNavigate),
onMenuItemClickRef = useRef(onMenuItemClick);
return (
<Menu
label={<RoundedImage src={url} alt={fullName} />}
items={[
{ label: `Logged in as: ${fullName}` },
{
label: "Liked articles",
onClick: () => onMenuItemClickRef.current("/liked-articles")
},
{
label: "Edit profile",
onClick: () => onMenuItemClickRef.current("/profile")
},
{ label: "Logout", onClick: () => console.log("Logging out") }
]}
/>
);
};
Would it also make sense to replace:
const onMenuItemClick = urlToNavigate => history.push(urlToNavigate)
with:
const onMenuItemClick = useCallBack(urlToNavigate => history.push(urlToNavigate), [urlToNavigate])
so it changes only when urlToNavigate changes?