Lecturer: We have a React app. We can enter our name and press this button. It will show how many clicks we have. We do this by keeping track of the count and the name. We compute this label every time we render and display it down here.
Let's import useMemo from React. We can use useMemo to cache this value. Let's say that our label now equals useMemo, and useMemo takes a function. The return value of this function should be this label that we're already computing.
To see how many times this runs, let's put a console statement here. If we save and use this, and expand the console here, we can see it computed once when it reloads. It computes every time we press the button, but it also computes every single time we type a letter into this box.
To prevent that, we can pass an array of dependencies to useMemo. This array of dependencies represents any values inside of this function that we need to compute the output.
For us, that's just the count. We can save this. You can see it computes once, when the component reloads, and once every time we press the button. Now, if we type our name it doesn't compute again, because name is not included in these dependencies.
We can keep pressing the button. It keeps computing once every time the count changes. If we didn't put anything in this array -- and save that -- this button would never work. This is computed once when the component loads, but it would never be computed again. We always want to keep all of our dependencies necessary in this array.
Finally, we don't want to rely 100 percent on this function only being called when these dependencies change. The React docs say that this may be called more often for memory reasons, for example. But it is a way to suggest a performance improvement by only computing a value when certain dependencies change.