Skip to content

React Component State API

Howie Reith edited this page Sep 27, 2019 · 10 revisions

The purpose of this section is to build competency with the React State API by examining an example application.

Exercise 1:

  1. Navigate to the state-api directory and run the following commands:

    npm install
    npm start
  2. Once the app loads, play the Name that Pirate game to familiarize yourself with the app

  3. Open the state-api folder using your favorite editor (your favorite editor should be vim, but anyway...) and familiarize yourself with the React components

Important Concepts:

  • All state is maintained in React.Component state and props. Therefore, state is localized to each component.

    • props are immutable
    • state is mutable.
  • While state is mutable, the means of mutation is constrained to the setState function.

    • setState informs the component and its children to re-render based on the new state.
    • Any mutations outside of setState will NOT trigger a re-render.
  • State is shared between components via props.

    • Some props simply pass static data
    • Other props pass functions that can pass data back out of a component. (See example below)
    // When an answer is clicked, it passes its pirate property to it's parent
    // via the its onSelected property.
    // Answer.js
    ...
    <div
      className="card mb-3 answer"
      onClick={() => {
        if (!props.disabled) props.onSelected(props.pirate);
      }}>
    ...
    
    // GameBoard sets Answer's onSelected property to its own
    // handleAnswerSelected method. In this way, the parent (GameBoard) is able
    // to get data from it's child (Answer)
    // GameBoard.js
    ...
    <Answer
      key={p.name}
      pirate={p}
      onSelected={this.handleAnswerSelected}
      disabled={p.disabled}
    />
    ...

Exercise 2:

  1. Add a Reset Score button to the state-api app. When clicked, the button should update the correct and incorrect counts to zero.

Pros

  • Simplicity
  • Little to no "magic" - no hidden logic
  • Negates the need for external libraries which lead to compatibility complexity.

Cons

  • Data sharing is only possible via a component Parent/Child relationship

Next

Clone this wiki locally