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

    Track Values Over the Course of Renders with React useRef in a Custom usePrevious Hook

    Kent C. DoddsKent C. Dodds
    reactReact
    ^16.7.0-alpha

    Our hook to track the previous values looks pretty useful, so let's extract that into it's own custom React Hook called usePrevious.

    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: Let's go ahead and take this a step further and extract some more Hooks that could be potentially useful elsewhere in our code base. Like this, for instance. It could be useful to be able to keep track of previous value over the course of renders.

    I'm going to take this. I'll pull this out entirely, and I'm going to make a new Hook called usePrevious. That's going to take a previous value, and I'm going to paste that in there.

    We're going to get a ref. We'll just make this more generic. We'll just call it ref. The current is going to be the value. What will we return? Let's go ahead and return the ref.current. We'll just return the current value. We don't need to return the entire ref.

    Let's go back in here. We'll say usePrevious, and we're going to get our previous inputs. Our inputs that we want to keep track of is this variable and query array here. Now we're getting the same thing that we had before, except we no longer need to use .current, because this is the actual value that we care about.

    In review, to make usePrevious, we simply made a function that accepts a value. We created a ref to keep a reference of that previous value. Then, in an effect, we have a callback that runs after every single time our component renders where we update the current value to that value, and then we return ref.current.