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.


    Track Async Requests with React's useState Hook


    The useState Hook is the best way to track state in React. It's capabilities aren't limited to known values either. State can be set with asynchronously resolved values as well — like the result of a fetch request. Wrapped promises can be given to useState to communicate promise status for state transitions.



    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: Now that our component is properly set up to fetch a Pokemon with an ID and communicate promise status to Suspense and error boundaries, let's add the ability to see the next Pokemon.

    To do that, we need a place to store our state. For that, there's no better place than React useState. As an initial state, I want to pass in our Pokemon, but we're going to have a naming collision here. As a pattern, I refer to this as initialPokemon and change the name up here as well.

    Now, I'm free to use the version that I get from useState as Pokemon, keeping everything in my component the same. It can't be additionally helpful to call this a resource and let Pokemon read that Pokemon resource only once.

    As I interpolate other values across this component, as it gets larger, I don't have to keep calling a read. It's cosmetic but it demonstrates how quickly these names become polluted against each other.

    We've got our initial Pokemon in state and we're using that state version of our Pokemon. We can set state by assigning this setPokemonResource function.

    Let's add a button. Button type = button and it'll have the text "Next." This is where the magic happens. On click, we want to set our Pokemon resource.

    What do we set it with? We can just fetch the next Pokemon. As long as we wrap it with our suspensify function, everything will work as we expect. Format, save and give it a try.

    When we press this again, we're going to keep getting Ivysaur because we've hardcoded this, too, in here. But we can pull that previous value off of our Pokemon state, Pokemon.ID+1.

    Now, as we click through, it will fetch a new Pokemon every time.