useState Hook in React
What Is useState?
In React, useState is a special Hook that lets you add something called state to your functional components.
But what exactly is state?
Think of state as a way for your component to "remember" things. For example, imagine you’re building a simple counter app. The counter’s number will change every time you click a button. This number is your component's state because it keeps changing, but the component needs to "remember" the latest value.
Without state, your component would forget the number each time it re-renders, and it would be stuck showing the same value.
The useState Hook lets your component remember and update values over time.
Why Do We Need useState?
Before we had Hooks, we could only add state in class components. If you wanted a button to update a number, or a form to store user input, you’d have to write more complicated code using classes. But with useState, you can do this directly in functional components, making it much simpler.
The useState Hook makes functional components more powerful by allowing them to keep track of changing values, such as:
- A counter that increases when a button is clicked.
- Text that a user types into an input field.
- Whether something is open or closed, like a dropdown menu.
In short, useState is the easiest way to handle changing data in a React app.
How Does useState Work?
Let’s walk through how the useState Hook works, step by step. Here’s how you use it in a functional component:
import React, { useState } from 'react';
function ExampleComponent() {
// 1. Create a state variable and a function to update it
const [count, setCount] = useState(0);
return (
<div>
<p>The current count is: {count}</p>
<button onClick={() => setCount(count + 1)}>Increase Count</button>
</div>
);
}
export default ExampleComponent;
Breaking It Down for Beginners
Let's break this code into smaller pieces so you can fully understand what's happening:
Import useState
First, at the top of the file, we import the useState Hook from React. You always need to import Hooks like useState before you use them in your component.
import React, { useState } from 'react';
Create State Variables
Inside your functional component (ExampleComponent), you create something called a state variable. The useState Hook helps you do this.
const [count, setCount] = useState(0);
This line does a few important things:
count: This is the state variable. It stores the current value of the counter, which starts at 0. Every time the state changes, React will remember the new value.setCount: This is the function that we use to update the value ofcount. Whenever you want to change the counter’s value, you callsetCount.useState(0): This tells React thatcountshould start at 0. The 0 insideuseState()is the initial state, meaning the first value thatcountwill have when the component loads.
Display the State Value
Inside the return part of the component, we show the current value of count using curly braces {count}. This tells React to display the value of count on the screen.
<p>The current count is: {count}</p>
Update the State
We also create a button that, when clicked, will increase the count by 1. The button uses the onClick event to call the setCount function, updating the state.
<button onClick={() => setCount(count + 1)}>Increase Count</button>
Every time you click the button, setCount(count + 1) will update count by adding 1 to the current value. React will then re-render the component to show the new value of count on the screen.
What Does useState Actually Do?
Let’s take a closer look at what’s happening:
- Initial state: When the component first loads,
useState(0)gives thecountvariable its initial value, which is 0 in this case. - State changes: Each time you click the button, the
setCountfunction updates the state. React then updates the component with the new value. - Re-rendering: Whenever the state changes, React automatically re-renders the component to show the updated value of
count.
This is how your component "remembers" things like the number of times a button has been clicked — through state.
Important Things to Know About useState
- State is only remembered inside the component: The state created with
useStateonly exists in the component where you declare it. Each component can have its own state that doesn’t interfere with other components. - State triggers re-rendering: Anytime you use the function from
useState(likesetCount), React will update the component with the new value and re-render it on the screen. - State can be any type: The value in
useStatedoesn’t have to be just a number. You can useuseStatewith strings, booleans, objects, arrays — anything that can change over time.
More Real-Life Examples
Here are some examples of how you might use useState in real-life situations:
Tracking Form Input
const [name, setName] = useState('');
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<p>Your name is: {name}</p>
name is the state that stores the user’s input.setName updates the state every time the user types something new in the input field.
Toggling Visibility
const [isOpen, setIsOpen] = useState(false);
<button onClick={() => setIsOpen(!isOpen)}>
{isOpen ? 'Close Menu' : 'Open Menu'}
</button>
{isOpen && <div>This is the menu!</div>}
isOpen is the state that keeps track of whether the menu is open.setIsOpen toggles the state between true and false whenever the button is clicked.
Conclusion: useState Makes Functional Components Powerful
To wrap up:
useStatelets your component "remember" and update values (like a counter or form input) over time.- It’s an easy way to add state to your functional components.
- Using
useState, you can build interactive apps that change based on what users do.
In the next lesson, we’ll look at another important Hook: useEffect, which lets you handle side effects like fetching data or setting up timers when your component renders.