Home
React
React Hook: useState()
Daniel Nguyen
Daniel Nguyen
July 07, 2025
1 min

useState is a fundamental React Hook that allows function components to store values between renders and update the UI when those values change.

1. What Is useState?

useState returns an array containing the current state and a setter function.

const [state, setState] = useState(initialValue);

Example:

function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}

When the button is clicked, React updates count and re-renders the component.

2. Functional Updates

When the next state depends on the previous state, use a functional update to ensure React calculates the new value from the previous state.

setCount((prev) => prev + 1);

This is especially useful when performing multiple updates in the same event handler.

setCount((prev) => prev + 1);
setCount((prev) => prev + 1);
setCount((prev) => prev + 1);

React processes these updates in sequence, increasing the count by three.

3. Updating Objects and Arrays

React state should be treated as immutable. Create new objects or arrays instead of modifying existing state directly.

Objects:

const [user, setUser] = useState({ name: "Daniel" });
setUser((prev) => ({
...prev,
name: "Alex",
}));

Arrays:

const [items, setItems] = useState<string[]>([]);
setItems((prev) => [...prev, "React"]);

Creating new references allows React to detect state changes correctly.

4. Lazy Initialization

If computing the initial state is expensive, pass a function to useState instead of calculating the value on every render.

const [value, setValue] = useState(() => computeInitial());

React uses the function’s return value to initialize the state. The initializer may run twice in development Strict Mode, so it should be pure.

5. Colocate State

Keep state in the component that needs it whenever possible. This reduces unnecessary state sharing and keeps components easier to maintain.

function SearchInput() {
const [query, setQuery] = useState("");
return (
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
);
}

6. Lift State Up

When multiple components need the same state, move it to their closest common parent and pass the value and update function through props.

function App() {
const [query, setQuery] = useState("");
return (
<>
<SearchInput query={query} onChange={setQuery} />
<SearchResults query={query} />
</>
);
}

Now both components share the same source of truth.


Tags

#ReactHook

Share

Daniel Nguyen

Daniel Nguyen

Frontend Developer

Frontend developer specializing in React, Next.js, and JavaScript. Writing practical guides on modern web development at Dev98.

Expertise

React
Next.js
JavaScript
TypeScript
Python

Social Media

githublinkedinyoutubewebsite

Related Posts

React Hook
React Hook: useRef()
July 10, 2025
1 min
Dev98

Dev98

React · Next.js · Web development