All about useState
What useState() does
useState() is a hook for storing state inside a function component.
It lets you "remember" a value between renders and update it, triggering a re-render of the component.
Syntax
const [state, setState] = useState(initialValue);initialValueis the initial state value (a number, string, object, array, and so on)- Returns an array of two elements:
- the current state value
- a function to update it
What useState() returns
const [count, setCount] = useState(0);countis the current state value (for example,0)setCountis the function that changes the state
How to change state
To change the state, call the setCount() function with a new value:
setCount(5);or based on the previous state:
setCount(prev => prev + 1);Important:
You cannot mutate state directly (count++),
because React will not know that the component needs to re-render.
The update must go through the setter (setCount).
Example - a counter
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0); // 0 - initial value
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}On every click:
setCount(count + 1)is called- React updates
count - The component re-renders with the new value
Updating based on the previous value
If the new state depends on the old one, use the functional form:
setCount(prev => prev + 1);This guarantees a correct update, even if React batches several setCount calls together.
What to remember
| Rule | Why |
|---|---|
Do not mutate state directly (state = ...) | React will not know about the change |
| You can store any type (numbers, objects, arrays) | useState is universal |
Calling setState re-renders the component | It triggers a new render |
| Updates are asynchronous | React may batch them for optimization |
Example with an object
const [user, setUser] = useState({ name: "Tim", age: 25 });
// Update a single field
setUser(prev => ({ ...prev, age: prev.age + 1 }));You cannot write user.age = 26; - that will not change the state in React.
Summary
| Question | Answer |
|---|---|
What does useState() do | Adds internal state to a function component |
What does useState() return | An array: [current value, function to change it] |
| How do you change state | Call setState(newValue) or setState(prev => nextValue) |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.