Member-only story
Today I’m reviewing the React hooks, and I actually happen to write a book called “Designing React Hook” if you are interested. And I went to the React website, and read the description on the first line: “useMemo
is a React Hook that lets you cache the result of a calculation between re-renders.” I stopped there, and I have to write a Medium about it, because there’s couple of issues in that line, in some way, that line is wrong.
First of all, to understand what the useMemo
is, we should better approach it from the source code level:
const a = useMemo(() => { return 'hello' })
We hardly use the hook useMemo
without the second parameter, but if I remember correctly, the second parameter can be omitted, and if so, the above line should almost behaves like below:
const a = 'hello'
I know what you will say, yes useMemo
is an assignment statement in that way. Not doubt about that. If you start from there, you can’t be too wrong.
Assignment
Now let me add some flavour back to this hook. So what’s so special about it is when to get a new value. For example, it can get a new value only at the mount and once. Or it can get a new value when a condition is met. And all these can be setup the same way we use useEffect
: