usestate

what is useState() ?

  • Profile picture of Mcs
  • by Mcs July 2, 2025

The React useState Hook allows us to track state in a function component. State generally refers to data or properties that need to be tracking in an application.

What is "state"?

State is data that changes over time (like a counter, form input, or toggle), When state changes, the component re-renders to reflect the new data

Basic Syntax

const [stateVariable, setStateFunction] = useState(initialValue);

  1. stateVariable: current value of the state
  2. setStateFunction: function to update the value
  3. initialValue: starting/default value

Example: Counter App

import React, { useState } from 'react';

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

 return (
   <>
     <h2>Count: {count}</h2>
     <button onClick={() => setCount(count + 1)}>Increase</button>
   </>
 );
}

When you click the button:
  1. setCount() updates the value of coun
  2. The component re-renders with the new count

Example: Input Field (Controlled Component)

function NameForm() {
 const [name, setName] = useState('');

 return (
   <>
     <input
       type="text"
       value={name}
       onChange={(e) => setName(e.target.value)}
     />
     <p>Hello, {name}!</p>
   </>
 );
}

Summary

ConceptDescription
useState()Adds local state to function components
Updates withsetStateFunction(newValue)
TriggersRe-render on state change
Initial ValueSet in useState(initialValue)