React State and Props

2019-03-21

The first time I learned about React state and props, I was confused and incorrectly implemented it in a project until I read more about it and understand the differences between those two. Therefore, I want to share how to use state and props properly in React.

Both state and props are variables in a React component. One obvious difference would be: props are variables (or should I say: constants) passed down to a child component, it is a way of communication between parent and child components. Take a look at the code below:

<Header title='Hello World' />

The Header component above is receiving a title as props with value "Hello World". It can be accessed inside the Header component using this.props.title. Another difference would be: props are immutable while states are mutable, and the way to change state is via a function called setState. A state is usually used to hold data that changes over time, and changes in the state causes that component to re-render.

A state is usually initialised inside a constructor of a component, like the code below:

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      color: 'blue';
    }
  }
}

As the above state initialised, we can later change the data inside the state, for example, color can be changed to red via the code below:

this.setState({color: 'red});

One common mistake for a beginner user of React is initialising state from props. Many would say that this is an anti-pattern because it creates a second source of truth which can lead to bugs. However, there is a trick as this quote:

It's not an anti-pattern if you make it clear that the props is only seed data for the component's internally-controlled state

So I think as long as we follow the rule above, bugs can be avoided.