0
0
Reactframework~5 mins

useState hook introduction in React

Choose your learning style9 modes available
Introduction

The useState hook lets you add and keep track of changing data in a React component. It helps your app remember things like clicks or typed text.

When you want to remember a number that changes, like a counter.
When you need to store text typed by a user in a form.
When you want to toggle something on or off, like showing or hiding a menu.
When you want to update the screen based on user actions.
When you want to keep track of simple data inside a component.
Syntax
React
const [state, setState] = useState(initialValue);

state is the current value you want to remember.

setState is a function you call to change that value and update the screen.

Examples
This creates a number state starting at 0, often used for counters.
React
const [count, setCount] = useState(0);
This creates a text state starting empty, useful for input fields.
React
const [name, setName] = useState('');
This creates a true/false state to show or hide something.
React
const [isVisible, setIsVisible] = useState(true);
Sample Program

This simple component shows a number and a button. Each time you click the button, the number goes up by one. The useState hook keeps track of the number and updates the screen.

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

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

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

export default Counter;
OutputSuccess
Important Notes

Always call useState at the top level of your component, not inside loops or conditions.

Calling the setter function (like setCount) tells React to update the screen with the new value.

You can use any type of value in useState: numbers, text, true/false, or even objects.

Summary

useState lets your React component remember and change data.

It returns the current value and a function to update it.

Updating state causes React to refresh what the user sees.