In this article, we analyse few arrow functions found in open source projects that are passed in as a parameter to useMemo or useCallback. I found these below list of functions in the wild, there could be more use cases but let’s control our sample size for this analysis.
useMemo and the arrow function
Let’s first understand what a useMemo is. useMemo is a React Hook that lets you cache the result of a calculation between re-renders.
const cachedValue = useMemo(calculateValue, dependencies)
Read more about
useMemo in Documenso
, you will find the below code snippet.
const disabledMessage = useMemo(() => {
if (remaining.documents === 0) {
return team
? msg`Document upload disabled due to unpaid invoices`
: msg`You have reached your document limit.`;
}
if (!session?.user.emailVerified) {
return msg`Verify your email to upload documents.`;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [remaining.documents, session?.user.emailVerified, team]);
In this case, results are cached based on these below values between re-renders:
remaining.documents
session?.user.emailVerified
team
useMemo in Tisqleditor
says that —
“
Just as {} creates a different object, function declarations like function() {} and expressions like () => {} produce a different function on every re-render. By itself, creating a new function is not a problem. This is not something to avoid! However, if the Form component is memoized, presumably you want to skip re-rendering it when no props have changed. A prop that is always different would defeat the point of memoization.
“
At this point, it is also worth mentioning useCallback.
useCallback
This below explanation is picked from .
useCallback usage in Postiz
, you will find the below code snippet.
const Page: FC<{ page: number; group: string; refChange: any }> = (props) => {
const { page, group, refChange } = props;
const fetch = useFetch();
const { message } = useContext(MarketplaceProvider);
const visible = usePageVisibility(page);
const loadMessages = useCallback(async () => {
return await (await fetch(`/messages/${group}/${page}`)).json();
}, []);
loadMessages contains a cached result except it does not contain any dependencies. Interesting. The component in which this function is defined has the following signature:
const Page: FC<{ page: number; group: string; refChange: any }> = (props) => {
About us:
At . We have developed reusable
SOCIAL SHARE CARD GENERATOR