useMemo usage in Documenso, an open-source Docusign alternative.
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.
Documenso is as an open-source Docusign alternative. I have to admit, Documenso is good!!! I like its user interface and the best part is this is open-source and built using Next.js. You can read their source code to learn best practices such as uploading files, rendering pdf with quality in Next.js and so much more. I have added this repository to my collection to study in depth and hopefully produce some articles like this one in the future.
tisqleditor is a codeMirror6 based SQL code editor which is used in TiDB Cloud Console. I am not sure what a TiDB cloud console is but we are interested in useMemo with arrow function as its parameter.
In the above image, you will find that activeFile is assigned the value returned by useMemo call that has two dependencies. activeFileId, openedFiles. This means activeFile results are cached between re-renders.
React docs 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.
This looks clunky! Memoizing functions is common enough that React has a built-in Hook specifically for that. Wrap your functions into useCallback instead of useMemo to avoid having to write an extra nested function:
The two examples above are completely equivalent. The only benefit to useCallback is that it lets you avoid writing an extra nested function inside. It doesn’t do anything else. Read more about useCallback.
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:
Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.