3 Different Examples - How State Works in React?

In React, state refers to an object that holds the data that determines the behavior and rendering of a component. When the state of a component changes, React will automatically re-render the component to reflect the updated state. Here are some examples to illustrate how state works in React:

1. Counter component:

In a class component, you can initialize the state within the constructor method using the this.state property. To update the state, you should use the this.setState() method, which accepts an object with the updated state properties or a function that returns the updated state based on the previous state.

Example:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);
  }

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}

In this example, we use the useState hook to initialize the state of the count variable to 0. We also define a handleClick function that updates the count state by calling the setCount function with the new value. Whenever the button is clicked, the handleClick function is called, which updates the state and triggers a re-render of the component.


2. Input component:

import React, { useState } from 'react';

function Input() {
  const [text, setText] = useState('');

  function handleChange(event) {
    setText(event.target.value);
  }

  return (
    <div>
      <input type="text" value={text} onChange={handleChange} />
      <p>You typed: {text}</p>
    </div>
  );
}

In this example, we use the useState hook to initialize the state of the text variable to an empty string. We also define a handleChange function that updates the text state whenever the user types in the input field. We bind the value of the input field to the text state using the value prop, and we listen to the onChange event to update the state whenever the input field value changes.


3. Todo list component:

import React, { useState } from 'react';

function TodoList() {
  const [todos, setTodos] = useState([]);

  function handleAddTodo() {
    const newTodo = prompt('Enter a new todo:');
    setTodos([...todos, newTodo]);
  }

  return (
    <div>
      <button onClick={handleAddTodo}>Add todo</button>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>{todo}</li>
        ))}
      </ul>
    </div>
  );
}

In this example, we use the useState hook to initialize the state of the todos variable to an empty array. We also define a handleAddTodo function that prompts the user to enter a new todo item, adds it to the todos state using the spread operator, and triggers a re-render of the component. We render the list of todos using the map function, and we use the key prop to give each todo item a unique identifier.

In summary, state is a fundamental concept in React that allows components to hold and update data dynamically. By using the useState hook, we can easily create and manage state in functional components, and React will automatically re-render the component whenever the state changes.


Most Helpful This Week