Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Efficiently Derive Values in React using useMemo

    Paul McBridePaul McBride
    reactReact
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.

    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.