DEV Community

Aman Kureshi
Aman Kureshi

Posted on

🧠 React useState Hook β€” Mastering State in Functional Components

The useState hook allows you to add state to your functional components β€” something only class components could do before React 16.8.

πŸ“Œ Basic Example:

import { useState } from "react";

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

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}
Enter fullscreen mode Exit fullscreen mode

✨ Key Points:
β€’ useState returns [value, setter]
β€’ Calling the setter (setCount) re-renders the component
β€’ You can store any type: number, string, object, or array

πŸ“˜ Example with Object:

const [user, setUser] = useState({ name: "Aman", age: 22 });
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Tip:
When updating state based on the previous value, always use the callback form:

setCount(prev => prev + 1);
Enter fullscreen mode Exit fullscreen mode

useState is the foundation of all interactivity in React πŸš€

Top comments (0)