0
0
Reactframework~5 mins

What is state in React

Choose your learning style9 modes available
Introduction

State lets a React component remember information and change what it shows on the screen.

When you want to keep track of user input like typing in a form.
When you want to show or hide parts of the page based on user actions.
When you want to update a counter or timer that changes over time.
When you want to store choices a user makes, like selecting options.
When you want to refresh parts of the page without reloading everything.
Syntax
React
const [stateVariable, setStateFunction] = useState(initialValue);
useState is a React hook that creates a state variable and a function to update it.
The initialValue sets what the state starts as when the component loads.
Examples
This creates a number state called count starting at 0.
React
const [count, setCount] = useState(0);
This creates a text state called name starting empty.
React
const [name, setName] = useState('');
This creates a true/false state called isVisible starting as true.
React
const [isVisible, setIsVisible] = useState(true);
Sample Program

This React component shows a button and a number. Each time you click the button, the number increases by one. The number is stored in state so React remembers it and updates the screen.

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

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

export default ClickCounter;
OutputSuccess
Important Notes

State updates are asynchronous, so React batches changes for better performance.

Always use the setState function to change state, never change state variables directly.

State only exists inside the component where it is declared.

Summary

State stores information that can change and affect what the component shows.

Use useState hook to create and update state in React functional components.

Changing state causes React to update the screen automatically.