How to Use the useState Hook in React

How to Use the useState Hook in React

In React, useState is one of the most commonly used Hooks.

It allows you to add state (data that changes over time) to your functional components. Like the number of items in a shopping cart, a user’s login status, or even the theme of your app (dark mode or light mode).

Why Do We Use useState?

Before React Hooks, state management in components was only possible with class components. But with the introduction of Hooks, like useState, you can now manage state directly in functional components!

How Does useState Work?

You can think of useState as a function that create and manage state in a functional component. It returns two things:

  • The current state value

  • A function to update that value

Example: Counter with useState

Let’s say we want to create a simple counter that increases by 1 every time you click a button. Here’s how we do it using useState:

What’s happening here?

  • use useState(0) to set the initial state of count to 0.

  • count holds the current state value, and setCount is the function used to update that value.

  • Every time the button is clicked, increment function runs, calling setCount to update.

Now you know how to use useState hook.

CodeBetter 💻


Stay updated with my articles ....

Connect with me on:

📩 Subscribe to Newsletter, 👨🏻‍💻 LinkedIn, 🌍 Personal Website, and 📸 Instagram,🎬 YouTube