← React Beginner Questions - Set 4 Q35

What is lifting state up in React?

React Beginner Questions - Set 4

Two siblings need the same value, so the state moves to their parent and travels down as props.

Example

import { useState } from 'react';

function CelsiusInput({ value, onChange }) {
  return <input value={value} onChange={e => onChange(Number(e.target.value))} />;
}

function Fahrenheit({ celsius }) {
  return <p>{celsius * 9 / 5 + 32} °F</p>;
}

export default function Converter() {
  const [celsius, setCelsius] = useState(20);   // lives in the parent

  return (
    <div>
      <CelsiusInput value={celsius} onChange={setCelsius} />
      <Fahrenheit celsius={celsius} />
    </div>
  );
}

What to notice

← Back to the question list