Mind of React: Should I Add an Item to State, or a Variable in render()?

Photo of a plastic brain with React logo on it

When gardening, you go to the shed, and in your bucket of garden tools, you see a medium sized garden trowel, and a similar trowel with a pointed nose. You decide you need to bring them both with you to plant your cactus, but was this really necessary? You could have used just one. Similarly, in React, we want to place as few “tools” (state items) as possible in our state, to keep things simple.

I was going over a React tic-tac-toe tutorial, and I noticed something odd. There was a variable declared in render() to set the display message for whose turn it was to go next. I was wondering why this variable was placed into render(), and not into it’s own state.

  render() {
    //why do they put status in render, not in state? 
    const status = `Next player: ${this.state.xIsNext ? 'X' : 'O'}`;
...

After some pondering, I came to the conclusion that the reason the display message was not given it’s own state was that the display message was based on a state item that already existed! Since the game already kept track of which player was next using the state item xIsNext, it didn’t make sense to create a new state item to keep track of the state message seperately. Since xIsNext is a Boolean, the value of the Boolean could be used to determine the display message. This was in fact how the state item was being used already. The state item didn’t contain an “X” or “O” for which player was next. The function that decided what to mark the next square was also based on the Boolean:

  handleClick(i){
    const squares = this.state.squares.slice(); 
    squares[i] = this.state.xIsNext ? "X" : "O";
    this.setState({
      squares,
      xIsNext: !this.state.xIsNext,
    })
  }

This showed a helpful point when deciding what to place into state. A Boolean is more useful and fluid in state than a string. You can use it in more places, and it simplifies the values in state, and the code overall. The same would be true for a number, as opposed to a string. Generally, numbers are more usable and plastic than strings. So when choosing what value to use in state, it’s best to go as simple as possible, to allow re-usage of that state in multiple places where the value of the state is relevant, and to avoid creating redundant state items.

Next time gardening, think about all of the things one tool could be used for, and it could be helpful in simplifying all the items you need to take with you to help your new plant join the family!

Picture of an azure blue house with many cactuses planted in front of it in the foreground
Photo by Edward Hart

Brain photo by Natasha Connell

Subscribe to new blog posts