React state management

From wikinotes

HTML forms in react behave similarly to html,
but react encourages you to mirror form state changes within your react components so they can be the source-of-truth.


official tutorial

Mirroring Form State

A text input maintains state in the browser when the user changes text.
It is encouraged to mirror this within your react component, to ensure your state matches what is rendered to screen.

// copied from official tutorial
class NameForm extends React.Component {
  constructor(props) {
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);

  handleChange(event) {

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
          Name: <input type="text" value={this.state.value} onChange={this.handleChange} />

        <input type="submit" value="Submit" />

Lifting State Up

The previous approach becomes especially useful if one component refers to state from multiple child components.
Using this approach to manage the render ensures that your changes are always synchronized within your parent-component's state.

Since events travel downwards, your intercepting of the rendering (and passing state as params),
ensures the rendered state always updates all involved components together,
ensuring your state is always consistent.

// copied form official tutorial
class Calculator extends React.Component {
  constructor(props) {
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', unit: 'c'};

  // changes to unit change the rendered `BoilingVerdict`
  // we want to make sure both 'unit' and 'temperature' are updated together
  handleCelsiusChange(temperature) {
    this.setState({unit: 'c', temperature});

  handleFahrenheitChange(temperature) {
    this.setState({unit: 'f', temperature});

  render() {
    const unit = this.state.unit;
    const temperature = this.state.temperature;
    const celsius = unit === 'f' ? tryConvert(temperature, toCelsius) : temperature;
    const fahrenheit = unit === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;

    return (
          onTemperatureChange={this.handleCelsiusChange} />
          onTemperatureChange={this.handleFahrenheitChange} />
          celsius={parseFloat(celsius)} />