How To Use useState Hook In React? See Example

What Is useState Hook?

The useState hook allows functional components in React to have state. It replaces the need for class components when managing data that changes over time.


Basic Syntax

const [state, setState] = useState(initialValue);
  • state → current state value
  • setState → function to update state
  • initialValue → starting value

Example: Counter

import React, { useState } from "react";

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

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

Example: Handling Input

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

  return (
    <div>
      <input 
        type="text" 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
      />
      <p>Your Name: {name}</p>
    </div>
  );
}

Tips for Using useState

  • Always use the setter function to update state
  • Don’t mutate state directly
  • You can store objects or arrays as state
  • Multiple useState calls can manage separate state variables

Conclusion

The useState hook is fundamental for managing state in React functional components, making UI interactive, dynamic, and easy to maintain.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *