React State & Props

Initializing State

We no longer use the constructor and instead define State property directly, like so,

class UserGreeting extends Component {
  state = { name: 'John' }
  render() {
    return <h1 className='name'>{this.state.name}</h1>
  }
}
export default UserGreeting

For Data Fetching use cases, State can be initialized inside thecomponentDidMount lifecycle.

hydrateState = () =>
  fetch('https://api.example.com/products')
  .then(response => response.json())
  .then(data => this.setState({data})
  .catch(error => console.error(error))

componentDidMount () {
  this.hydrateState()
}

Props

Only provide components with the necessary Props.

class UserGreeting extends Component {
  state = {
    user: {
      name: 'John',
      email: '[email protected]',
      age: 28
    }
  }

  render() {
    // Destructure nested object props for better readability
    const user = this.state.user
    return (
      <div>
        <NameTag name={user.name} /> // Instead of <NameTag user={user} />
        <EmailLink email={user.email} />
        <h4>{user.age}</h4>
      </div>
    )
  }
}
export default UserGreeting

Reference