Sometimes in a React component we need to derive some values by mapping or filtering props. This is a useful technique but can cause performance issues of you are processing a lot of data, or the component is rendered regularly. In this lesson you'll learn how to avoid this pitfall using the useMemo
hook.
Instructor: [00:00] Here, we have a react component that renders a list of users. We can filter those users by status. If we take a look at the code and how it works, we can see that we're rendering a user table and we have to pass the filtered users array in as a prop.
[00:17] Filtered users is derived from the props.users value that gets passed into our app component. This is an effective approach, but it does have some drawbacks. Every time state changes in a react component, the component will re-render. We can illustrate this by adding a log into this map function.
[00:38] If we take a look at the console, we can see that unnecessary work is logged 100 times. That's once for each user. By itself, this isn't really a problem. Where it starts to become an issue is that you'll notice that when we change the status of the filter, it gets logged 100 more times for each time the state changes.
[00:58] To solve this, we're going to import useMemo from React. We're going to wrap it around this map function. UseMemo expects a function as its first argument, so I'm going to turn this into a function. The second argument is an array of dependencies. Anytime any value in this array of dependencies changes, this function will run again.
[01:22] In this case, we only want that to rerun whenever the prop.users value changes, so I'm going to type that into this array. To confirm useMemo, we'll run this function any time props.users changes. Whatever gets returned from this function will be assigned to formatted users.
[01:44] If we look at the console, we can see that unnecessary work has been logged 100 times. That's unavoidable because we need to work on formatted users at least once. However, if we change the status, we can see that it doesn't get logged any more times. That's because the props.users value never changes. The callback function inside useMemo never runs again.