Skip to main content

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

javascript
const [state, setState] = useState(initialValue);
  • initialValue is the initial state value (a number, string, object, array, and so on)
  • Returns an array of two elements:
    1. the current state value
    2. a function to update it

What useState() returns

javascript
const [count, setCount] = useState(0);
  • count is the current state value (for example, 0)
  • setCount is the function that changes the state

How to change state

To change the state, call the setCount() function with a new value:

javascript
setCount(5);

or based on the previous state:

javascript
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

javascript
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:

  1. setCount(count + 1) is called
  2. React updates count
  3. 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:

javascript
setCount(prev => prev + 1);

This guarantees a correct update, even if React batches several setCount calls together.


What to remember

RuleWhy
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 componentIt triggers a new render
Updates are asynchronousReact may batch them for optimization

Example with an object

javascript
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

QuestionAnswer
What does useState() doAdds internal state to a function component
What does useState() returnAn array: [current value, function to change it]
How do you change stateCall setState(newValue) or setState(prev => nextValue)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.