@ZackArgyle 1. Start with plain React. 2. Lift state as needed. 3. Still feeling pain? Use Redux/Context/etc.

  • Currently, both components independently keep their values in the local state: – – However, we want these two inputs to be in sync with each other.
  • Since the props of both components are coming from the same parent component, the two inputs will always be in sync.
  • It will handle the change by modifying its own local state, thus re-rendering both inputs with the new values.
  • For example, if we enter 37 into the Celsius input, the state of the component will be: – – If we later edit the Fahrenheit field to be 212, the state of the will be: – – We could have stored the value of both inputs but it turns out…
  • The inputs stay in sync because their values are computed from the same state: – – Try it on CodePen.

Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor. Let’s see how this works in action.

Often, several components need to reflect the same changing data. We recommend lifting the shared state up to their closest common ancestor. Let’s see how this works in action.

In this section, we will create a temperature calculator that calculates whether the water would boil at a given temperature.

temperature as a prop, and prints whether it is enough to boil the water:

function BoilingVerdict (props) { if (props.celsius >= 100 ) { return

The water would boil.

; } return

The water would not boil.

; }

for the current input value.

class Calculator extends React.Component { constructor (props) { super (props) ; this .handleChange = this .handleChange. bind ( this ) ; this .state = {temperature: ” } ; } handleChange (e) { this . setState ( {temperature: e.target.value} ) ; } render ( ) { const temperature = this .state.temperature; return (

Enter temperature in Celsius:
) ; } }

Try it on CodePen.

Our new requirement is that, in addition to a Celsius input, we provide a Fahrenheit input, and they are kept in sync.

const scaleNames = { c: ‘Celsius’ , f: ‘Fahrenheit’ } ; class TemperatureInput extends React.Component { constructor (props) { super (props) ;…

Lifting State Up