State

In one sense, “state” means the current visual representation of the app on screen… In the React sense, “state” is an object that represents the parts of the app that can change. Each component can maintain its own state, which lives in an object called this.state. - Dave Ceddia

What is state in React?

class App extends React.Component {
  constructor(props) {
    super(props);

    // Must initialize state first
    this.state = { count: 0 };
  }

  handleClick() {
    // Increment the count when the button is clicked
    this.setState({
      count: this.state.count + 1
    }, function() {
      // setState is asynchronous! This function gets called
      // when it's finished.
      console.log("Job's done");
    });
  }

  render() {
    return (
      <div className="app">
        <div className="click-count">
          Button presses: {this.state.count}
        </div>
        <button onClick={this.handleClick.bind(this)}>
          Add One
        </button>
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('container')
);

Lifting State Up

What is lifting up state?

Asynchronous Updates & setState()

I heard you can pass a function to setState when should do that?

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state. — Rect Docs

If you know you’re going to use setState to update your component and you know you’re going to need the current state or the current props of your component to calculate the next state, passing in a function as the first parameter of this.setState instead of an object is the recommended solution. — Sophia Shoemaker

// state updates may be asynchronous

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));
// see post :: Using a function in `setState` instead of an object

// outside your component class
function increaseScore (state, props) {
  return {score : state.score + 1}
}
class User{
  ...
// inside your component class
  handleIncreaseScore () {
    this.setState( increaseScore)
  }
  ...
}

Handling State

How do I handle state?

How can I decouple state and UI?

Coming from jQuery… how do I adjust my mental modal to work with React / State?

Tip: 🤔 Use derived state when possible see code sample below:

class NameWithInitials extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      firstName: "",
      lastName: "",
      // Avoid creating state that can be derived from other state.
      // Example: The user's initials can be derived from the two items above.
      initials: ""
    };
  }

  render() {
    const { firstName, lastName } = this.state;
    // Instead generate the user's initials on the fly like this.
    // Or do so in a seperate function above
    return (
      <div>
        Initials: {firstName.charAt(0)} + {" "} + {lastName.charAt(0)}
      </div>
    );
  }
}

via @housecor - twitter link.

Handling Initial State

How do I handle Intial state?

Use the constructor method also see tip below.

class MyComponent1 extends React.Component{
    constructor(props){
        super(props);
        this.state = {myVal: 'val'}
    }
}

Tip: 🤔 You don’t need to declare a constructor in your React component to initialize state via @housecor:

// via @housecor https://twitter.com/housecor/status/866651617998897152
// Traditional way
class MyComponent1 extends React.Component{
    constructor(props){
        super(props);
        this.state = {myVal: 'val'}
    }
}

//Using public class field
class MyComponent2 extends React.Component{
    state = {
        myVal: 'val'
    }
}

Do I need to use the constructor?

https://hackernoon.com/the-constructor-is-dead-long-live-the-constructor-c10871bea599

How do I handle making state immutable in React?

Can I add state to function components in React?

Can I set state can use setState in componentDidMount and componentDidUpdate?