React in-depth

Joe Buza

  • What happens when you call setState?

  • What arguments can be passed to setState?

  • What is the difference between a controlled component and an uncontrolled component?

  • What does shouldComponentUpdate do and when to use it?

  • What is the difference between Class, Pure and Functional Component?

What happens when you call setState?

Merge

New State

Old State

Reconciliation

What arguments can be passed in setState?


this.setState(updater, callback)

this.setState(
  { toggled: true },
  () => {
    console.log('setState has finished and re-rendered.')
    console.log(this.state.toggled) // true
  }
)

this.setState(
  { toggled: false }
)

this.setState((prevState, props) => {
  return {
    toggled: !prevState.toggled
  }
})

1.

2.

3.

!this.state.toggled

What is the difference between Controlled and an

Uncontrolled Component?

Controlled

class ControlledForm extends Component {
  state = {
    username: ''
  }
  updateUsername = (e) => {
    this.setState({
      username: e.target.value,
    })
  }
  handleSubmit = () => {}
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          value={this.state.username}
          onChange={this.updateUsername} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}
class UnControlledForm extends Component {
  handleSubmit = () => {
    console.log("Input Value: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}

UnControlled

Controlled

UnControlled

What does shouldComponentUpdate do and when to use it?

class CounterButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: 1};
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
  }

  render() {
    return (
      <button
        color={this.props.color}
        onClick={() => this.setState(state => ({count: state.count + 1}))}>
        Count: {this.state.count}
      </button>
    );
  }
}

What is the difference between

Class, Pure and Functional Component?

Class Component

  • Lifecycle methods

  • Implement own shouldComponentUpdate

Pure Component

  • Introduced v15.3.0

  • Components with simple, no nested props/state

  • Performs shallow compare

Functional Component

  • Simple presentation

  • Can't define shouldComponentUpdate

  • Easy to test

Resources

Questions?

React in-depth

By Joe Buza

React in-depth

Will answer some of the confusing parts of React. Like how the reconciliation process works and what happens when you change states.

  • 1,356