React 18

Last Updated: 10/27/2023

Controlled Components

  • You can also use state hook to get the value of input fields in the form.
const [person, setPerson] = useState({name: "",
age: ""})
  • All inputs has change event which is triggered when user types keystroke
  • You can handle the change event and update the state variables every time the user type something in an input field.
onChange={(event) => setPerson({...person, name: event.target.value})}
onChange={(event) => setPerson({...person, age: parseInt(event.target.value)})}
  • Every time user enters/removes char component gets re-rendered
  • If you have a really complex form with a lot of elements, and you observe performance issues with this approach, then use the ref hook. But for the most cases, you're not going to experience that.

Single source of truth

  • All inputs have value prop for maintaining state
  • It is possible the value and react state may get out of sync, to solve make react single source of truth
  • Set value property
value={person.name}
  • input field always relies on the value in our state variable.
  • Value of input is not managed by DOM. It is stored and updated in component state
  • Input is referred to as controlled component when the state is controlled by react