useState – Making Components Interactive

🎯 What is useState?

  • useState is a React Hook.
  • It lets your component remember and update data (called “state”).
  • When state changes, React automatically re-renders the UI.

✅ 4.1 Example: Click Counter

import { useState } from "react";

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

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

function App() {
  return (
    <div>
      <h1>My App</h1>
      <Counter />
    </div>
  );
}

export default App;

🧠 Explanation

const [count, setCount] = useState(0);
  • count: the current value (initially 0)
  • setCount: a function to update the value
  • useState(0): sets the initial state

Then in your button:

<button onClick={() => setCount(count + 1)}>Increase</button>
  • When clicked, it calls setCount with count + 1
  • React re-renders the component with the new count!

🧪 Try It Yourself

  • Add a “Decrease” button to subtract from the counter.
  • Show a message if count === 0: "Start counting!"
{count === 0 && <p>Start counting!</p>}

🔄 React Re-renders on State Change

You don’t have to manually update the DOM — React does it automatically when you call setCount.


⚠️ Where Can I Use useState?

✅ Inside React components
❌ NOT inside loops, conditions, or plain JS functions

Keep Learning 🙂

Leave a Reply

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