Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

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

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Refactor Inlined React setState Function to a setState Updater Factory

    Erik AybarErik Aybar

    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.

    reactReact
    ^16.0.0
    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
    Transcript

    Transcript

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

    00:23 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.

    00:50 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.

    01:18 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.

    Discuss

    Discuss