State in React

Understanding State in React

WHAT IS IT

In functional components useState Hook lets you add state to your components. A state is way to store data in React. It changes over time. It can be anything. An example is user input. It could be a counter or a list of items too.

How it works:

You're keeping an eye on a list of to-dos in your mind. Each time a new task is added to the list the UI has to update. This updating reflects the change.

This is common scenario for using state. It is a crucial part of component development in React.


import React, {useState} from 'react';

function ToDoApp() {
  const [tasks, setTasks] = useState([]);
  const [task, setTask] = useState("");

  function addTask() {
    setTasks([...tasks, task]);
    setTask("");
  }

  return (
    
setTask(e.target.value)} />
    {tasks.map((task, index) => (
  • {task}
  • ))}
); }

Real life analogy:

Imagine managing a shopping list on a phone. You begin with list that's empty. Then you type in items. Add an item and your list updates. It shows everything you added.

2. State in Class Components

What is it?

Before introduction of Hooks state was managed inside class components. In class components state is defined as object. This object is manipulated using this.setState().

How it works:

Imagine an online poll. Users can vote for favorite options. We need to track the number of votes. When someone clicks a vote button, the vote count increases.


import React, { Component } from 'react';

class VoteCounter extends Component {
  constructor(props) {
    super(props);
    this.state = { votes: 0 };
  }

  incrementVotes = () => {
    this.setState({ votes: this.state.votes + 1 });
  };

  render() {
    return (
      

Votes: {this.state.votes}

); } } export default VoteCounter;

Breakdown:

  • State is object. It has votes property. State is this.state.
  • State gets updated using this.setState(). When someone clicks vote button component re-renders. It shows an updated number of votes.

Real-life analogy:

Picture situation. You're tracking people entering room using counter device. Each time someone enters you press button. Counter increases by one.

Analogy. Counter device. It represents state. Pressing button. That's like using setState() to update state. A person entering room is analogous to an event. The event triggers the state to change by one i.e. the counter to increase by one.

3. Lifting State Up

What is it?

Lifting state up is term used in sharing state situation. Two or more components need to share state. In such instances shared state is relocated. It moves up to the nearest common parent. From there parent sends it down to kids as props.

How it works:

Imagine you have two components. One component enters temperature in Celsius. Another represents equivalent temperature in Fahrenheit. They need to share temperature. A state holds this temperature. The shared state resides between these components.


import React, { useState } from 'react';

function CelsiusInput({ temperature, onTemperatureChange }) {
  return (
     onTemperatureChange(e.target.value)}
      placeholder="Enter temperature in Celsius"
    />
  );
}

function FahrenheitDisplay({ temperature }) {
  const fahrenheit = (temperature * 9) / 5 + 32;
  return 

Temperature in Fahrenheit: {fahrenheit}

; } function TemperatureConverter() { const [temperature, setTemperature] = useState(0); const handleTemperatureChange = (newTemperature) => { setTemperature(newTemperature); }; return (
); } export default TemperatureConverter;

Breakdown:

  • Parent component TemperatureConverter holds temperature state. It passes state down to CelsiusInput and FahrenheitDisplay.
  • CelsiusInput allows user to update the temperature. This is an interactive component. CelsiusInput also allows the user to type in a numerical value.
  • FahrenheitDisplay on the other hand shows the user the temperature. The temperature is presented in Fahrenheit.
  • CelsiusInput and FahrenheitDisplay are child components of parent component TemperatureConverter.
  • Temperature state is lifted state. It is lifted from child component to parent component.

Real-life analogy:

Imagine notebook. It is shared between you and a friend. You both need to write notes during a meeting. You both need to access the notebook. The notebook rests in middle of table. From there both of you can reach it.

This is how lifting state up works. It allows for multiple components to access and share same state.