One of the first things you'll need to understand when starting with React is managing state. We will talk about useState
hook today which will help you with this. This hook is super important because it lets us keep track of data that changes while your app runs. So, let's dive in and get you comfortable with the usage of it!
What is useState
?
In simple terms, useState
is a function that allows you to keep track of data in your React components. This “data” could be anything – like a number, a piece of text, or even a whole object. useState
lets us update that data and see those updates on the screen.
You can think of it as a "memory" of the component. Let's supose you build simple screen with a button and text displaying how many times the button was clicked. Our "memory" will be that number of clicks.
In other words - useState
is a hook for managing state in React.
Code example
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Let's walk through the code step by step:
- Setting up: We import
useState
from React. Then, inside our component, we executeuseState(0)
. The0
here is the starting value for count. Our "initial memory". - Destructuring:
useState(0)
returns an array with two items. We’re using destructuring assignment to name those two items:-
count
is the actual value (starts at 0) -
setCount
is the function we’ll use to update the count
-
- Updating state: When you click the button,
setCount(count + 1)
runs. This adds 1 to count, and React will re-render the component to show the new value.
Set function schedules the update
Set function (setCount
) doesn't change count instantly. Instead, React "schedules" the update. If you try to console log count
right after calling setCount
, it will show the old value.
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
console.log(count); // This will log the old value, not the updated one
};
return (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment</button>
</div>
);
}
You have to wait for the component to re-render instead to use the variable correctly.
State is immutable
In React, state should always be treated as immutable, meaning you shouldn’t modify it directly. Directly mutating state can cause bugs because React won’t detect the change, so it won’t trigger a re-render.
For example, if you’re working with an object or array, make sure to create a copy of the state before updating it. Look:
// Wrong: Direct mutation of state
user.name = 'New Name';
setUser(user);
// Right: Creating a new object to update state
setUser({ ...user, name: 'New Name' }));
Usage with Typescript
You can pass type parameter to your useState
call if you want to tell TypeScript what type of variable to expect:
const [user, setUser] = useState<User>(initialUser);
You can execute useState
without initial state:
const [user, setUser] = useState<User>();
React will then assume that the type of your variable is User | undefined
,
Wrapping up
So, these are absolute basics of the useState
hook that will allow you to build first applications with React! Any questions?
Top comments (0)