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
Become a member
to unlock all features

Level Up!

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


    Refactor Inlined React setState Function to a setState Updater Factory


    React's setState accepts an updater function that given current state returns new state. To better define and manage our setState usages, we can extract our inlined setState function to a setState updater factory. This enables us to give it a descriptive name, define required arguments, and ease future reuse, refactoring and composition for updating component state in our application.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Instructor: Instead of inlining this whole setState function here, what we can do is, we're going to write a function here. This is going to be our setState updater function. We will give it a descriptive name, which is going to be, "set tweet liked." It's going to need to know the tweet ID and also the new liked.

    Shall we be transitioning to liked or transitioning to unliked? This is going to return, essentially, what we had here. Now, rather than looking up the current state of it, we will just transition to using the new liked. We'll assume that when we invoke this, we know what we want. We'll update this usages of is liked to new liked.

    We'll be flipping that logic around, since we're assuming that the consumer of this is going to handle the toggling logic. Now to plug this in, we can invoke it here, "set tweet liked." The arguments that it requires is tweet ID and the new liked, which is going to be the opposite of the current liked, which we know we can look up by currying includes on our liked tweets.

    Now when we click this, we can see that the number is updating as well as the heart is updating appropriately. We have yet to handle the failure case.