React Holiday

Day 16: Mind the lifecycle gap

Today we’ll talk about things that don’t happen!

First, a new component

I’d like you to write a new component.

You’ll define this component with some state and event handlers for updating that state. Here are the instructions:

  • Name it PokemonPager
  • Set the initial state to have an id of 1
  • Render state.id in an h2 component
  • Renders two button components:
    • Clicking “Previous” decrements id
    • Clicking “Next” increments id

Create a new sandbox for your component. Try not to look ahead.

⚛️ 💪

World’s Worst Pokemon Pager

You’ve made a PokemonPager but it’s a bad one. That’s my fault.

I forgot that it needs to render a Pokemon.
Let’s fix that!

class PokemonPager extends React.Component {
  state = { id: 1 }

  render() {
    <div>
      <h2>{this.state.id}</h2>
      <Pokemon id={this.state.id} />
      ...

Now we see a big number 1 above Bulbasaur’s name and abilities.

What happens when we click the buttons?

Where’s Ivysaur?!?

Our number gets incremented but Bulbasaur remains the same.

The components are updating—we see that in the number—but Pokemon isn’t changing.

🤔

This is where I leave you

Here’s the problem:

The Pokemon component only fetches a Pokemon when it gets mounted.
It’s only mounted once. After that, it’s gets updated.

We need to fetch the next Pokemon in one of the updating lifecycle methods.

Read the docs on updating lifecycle methods. Find and use one of the methods to fetch a Pokemon every time the component receives a prop id.

Tinker with it

Use the workspace below and explore updating lifecycle methods.

Make an attempt and I’ll show you my recommendation tomorrow.

Read sections above carefully; they subtly suggest the right method. Don’t forget that most lifecycle methods take arguments.