React.js componentWillReceiveProps example

I’ve been using React.js for a while. Yet I didn’t really understand when to use some of the lifecycle methods. Today, I grokked one. So here’s a simple React.js componentWillReceiveProps example in case it helps someone else.

Official Documentation

The official docs at https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops do a good job of explaining it. The “for example, to reset it” bit in particular, makes a lot of sense. But, that’s with the benefit of hindsight.

For some reason I struggle to grok words, maybe it’s my age, but I like a nice example, including a good picture.

My Scenario

I’m building a pairs memory game. To try and build some separation, I have split the application state from the state of the board. I’ve done that as I don’t think, for example, the board should be aware of how many games have been played. Neither should the board know the quickest time the game was completed. (The app I’ve built can’t do any of those things, but that’s my thinking. Hey, I’m learning!)

I got to the state where I was trying to figure out what to do when completing the game. Or more accurately, how to reset all the cards to their initial state.

When the board is first created, inside the constructor of Board component I create all the cards. As this constructor is called only once I don’t need to care about it happening at another random time. But how to get a message to Board to tell it to reset/recreate the cards?

I knew how to pass a message from the child (Board) to the parent (App) as I’ve done that many times via passing a function as a prop. But getting the App to tell the Board to start a new game after the initial render was an unknown.

Parent to Child Communication

Parent to Child Communication

Maybe good picture was pushing it!

I feel silly writing this now as Parent to Child communication for data is via props. But again, that’s hindsight. I’m also clearly not alone as my first search found this http://stackoverflow.com/questions/37949981/call-child-method-from-parent. I’m sure that would’ve worked, but it felt wrong.

Enter, componentWillReceiveProps.

componentWillReceiveProps example

When the board detected the game was over, it called the “onGameOver” prop passed to it. So I’m working in the Parent (App) component.

Turns out, all you need to do is call this.setState() in the Parent (App) component. If you are passing props from Parent to child, the refresh will call componentWillReceiveProps.

So I added a boolean flag to the state of the Parent (App) component. Initialised it to false and passed it down to the Child (Board) component via props, i.e. newGame={this.state.newGame}.

The constructor of Board, which is only called once, ignores it. In componentWillReceiveProps I check for when it’s true, and then reset the board.

It does mean that every time I call this.setState in the Parent (App) I need to make sure newGame is false. But that’s a small inconvenience.

class App extends Component {

  constructor(props: Props) {
    super(props);

    this.state = { newGame: false };
  }

  render() {
    return (
      <Board
        onGameOver={() => this.setState({ newGame: true }) }
        newGame={this.state.newGame}
        />
    );
  }
}

export default App;


class Board extends Component {

    constructor(props: Props) {
        super(props);

        this.state = { tiles: this.generateNewTiles() };
    }

    detectGameEnded(){
        // ...
        this.props.onGameOver();
    }

    componentWillReceiveProps(nextProps: Props) {
        if (nextProps.newGame) {
            this.resetGame();
        }
    }
}

export default Board;

Request for feedback

I feel silly posting this as it seems obvious now. But I guess that’s the journey of learning. But, I might be missing something.

“It works on my machine” is great, but that doesn’t mean I’m correct. If I’ve missed something or I’m just plain wrong, please correct me. Use the comments below or on twitter, I’m more than welcome to all and any feedback.

2 Responses to “React.js componentWillReceiveProps example”

  1. A Person says:

    Thanks for writing this! I had the equivalent problem in a game I’m working on. I also have a “dumb” game component that knows only about what’s going on inside the current game. I needed a way for the user to abandon the current game and start a fresh one, and rather dumbly (in hindsight anyway) I thought this would be accomplished simply by passing new props to the game component (whose constructor takes those props and sets them as the game’s initial state values). Found this write-up and it helped. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *