0
0
Reactframework~5 mins

Updating state in React

Choose your learning style9 modes available
Introduction

Updating state lets your app remember and show new information when things change. It helps your app respond to user actions or data updates.

When a user types in a form and you want to save what they type.
When a button click changes what is shown on the screen.
When you get new data from the internet and want to display it.
When you want to toggle something on or off, like showing or hiding a menu.
Syntax
React
const [state, setState] = useState(initialValue);

// To update state:
setState(newValue);

// Or update based on previous state:
setState(prevState => updatedValue);

Use useState hook to create state in functional components.

Always use the setter function (like setState) to update state, never change state directly.

Examples
Set the count state to 5 directly.
React
const [count, setCount] = useState(0);
setCount(5);
Update count by adding 1 to the previous value.
React
setCount(prevCount => prevCount + 1);
Change text state from empty to 'Hello'.
React
const [text, setText] = useState('');
setText('Hello');
Sample Program

This component shows a number and two buttons. Clicking 'Increase' adds 1 to the number. Clicking 'Decrease' subtracts 1. The state updates and the number on screen changes.

React
import React, { useState } from 'react';

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

  return (
    <main>
      <h1>Count: {count}</h1>
      <button onClick={() => setCount(count + 1)} aria-label="Increase count">
        Increase
      </button>
      <button onClick={() => setCount(count - 1)} aria-label="Decrease count">
        Decrease
      </button>
    </main>
  );
}
OutputSuccess
Important Notes

State updates are asynchronous, so changes may not happen immediately.

Use the function form of setter when new state depends on old state to avoid bugs.

Always keep state updates pure and avoid side effects inside the setter function.

Summary

State holds data that can change in your component.

Use useState hook to create and update state.

Update state with the setter function to make your UI update automatically.