DEV Community

Tamilselvan K
Tamilselvan K

Posted on

Day-34 Getting Started with React's useState Hook

Today, I learned about the useState hook in React, which is a powerful feature used to manage state in functional components. To practice what I learned, I created a simple Counter App. It helped me understand how to update and display dynamic values in a React component.


What is useState?

The useState hook is a built-in React hook that lets you add state to your functional components.
Here’s the syntax:

const [state, setState] = useState(initialValue);
Enter fullscreen mode Exit fullscreen mode
  • state – the current value of the state.
  • setState – a function to update the state.
  • initialValue – the starting value of the state.

My Project: A Simple Counter

Here’s the code I wrote:

import { useState } from "react";

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

  return (
    <div>
      <div className="container">
        <h1>Count: {count}</h1>
        <button onClick={() => setCount(count + 1)}>+</button>
        <button onClick={() => setCount(count - 1)}>-</button>
        <button onClick={() => setCount(0)}>Reset</button>
      </div>
    </div>
  );
}

export default Counter;
Enter fullscreen mode Exit fullscreen mode

How It Works

  • useState(0) initializes the count with 0.
  • Clicking + calls setCount(count + 1) to increase the count.
  • Clicking - decreases the count.
  • The Reset button sets it back to zero using setCount(0).

Each time the state changes, React re-renders the component and shows the updated count.


Key Takeaways

  • useState helps make components dynamic and interactive.
  • React updates the UI automatically when the state changes.
  • Hooks can only be used inside functional components (not outside or in loops/conditions).

Next Steps

I plan to add an input box that captures a name using useState. Here's a preview:

const [name, setName] = useState("");
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Learning useState gave me a better understanding of how React apps work behind the scenes. Small projects like this boost my confidence and help me learn React step-by-step.

Top comments (0)