What is useState() in React?

Understanding useState in React

In React, useState is a built-in Hook that allows functional components to have state. Prior to the introduction of Hooks in React 16.8, only class components could manage state. Now, with useState, functional components can also keep track of values that may change over time, such as user inputs, toggle states, counters, and more.

1. What is useState?

useState is a Hook that returns an array with two elements:

  1. The current state value.
  2. A function to update this value.

When you call useState with an initial value, React sets up a state variable with that value. You can then update this state using the provided update function, which re-renders the component whenever the state changes.

2. Syntax of useState

const [state, setState] = useState(initialValue);
  • state: Holds the current state value.
  • setState: The function used to update the state value.
  • initialValue: The initial value of the state, which can be any data type—string, number, boolean, object, array, etc.

3. Example of Using useState

Let’s look at a simple counter example to illustrate how useState works.

import React, { useState } from 'react'; function Counter() { // Initialize state with `useState` Hook const [count, setCount] = useState(0); // Function to increment count const increment = () => setCount(count + 1); return ( <div> <p>Current Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); } export default Counter;

Explanation:

  • Initialization: useState(0) initializes the count state with a value of 0.
  • Updating State: setCount(count + 1) updates the count value by incrementing it.
  • Rendering: When setCount is called, React re-renders the component with the updated count value.

4. Using useState with Complex Data Types

useState can hold complex data structures like objects and arrays. However, when updating these structures, it’s essential to manage immutability by creating copies of the existing state.

Example with Objects

function UserProfile() { const [user, setUser] = useState({ name: 'Alice', age: 25 }); const updateName = () => setUser({ ...user, name: 'Bob' }); return ( <div> <p>Name: {user.name}</p> <p>Age: {user.age}</p> <button onClick={updateName}>Change Name</button> </div> ); }

Explanation:

  • Object Spread: setUser({ ...user, name: 'Bob' }) spreads the current properties of user and updates the name property, preserving immutability.

Example with Arrays

function TodoList() { const [todos, setTodos] = useState(['Learn React', 'Practice Coding']); const addTodo = () => setTodos([...todos, 'New Todo']); return ( <div> <ul> {todos.map((todo, index) => ( <li key={index}>{todo}</li> ))} </ul> <button onClick={addTodo}>Add Todo</button> </div> ); }

Explanation:

  • Array Spread: setTodos([...todos, 'New Todo']) creates a new array with the existing todos and adds 'New Todo' at the end.

5. Setting State Based on Previous State

When updating state based on its current value, use a function inside setState to access the previous state safely. This avoids potential issues due to asynchronous state updates.

const increment = () => setCount(prevCount => prevCount + 1);

In this example, prevCount is the previous state, ensuring the update is based on the latest state value.

6. Initial State as a Function

If the initial state is computationally expensive to create, you can pass a function to useState. This function only runs once during the initial render.

const [state, setState] = useState(() => computeExpensiveValue());

7. Key Points to Remember about useState

  • State Persistence: State persists between renders, but re-initializes only on the first render.
  • Asynchronous Updates: State updates may be batched and applied asynchronously.
  • Component Re-Rendering: Updating state triggers a re-render of the component.

8. Benefits of Using useState

  • Simplicity: Offers a simple way to manage component state without needing class components.
  • Flexibility: Can handle primitive data types and complex structures like objects and arrays.
  • Efficient Re-Renders: Only re-renders the components where the state has changed.

Conclusion

The useState Hook is a powerful tool for managing local component state in React functional components. It provides an easy-to-use syntax and promotes efficient re-renders, helping developers create interactive and dynamic applications. Understanding how to use useState with different data types and in various scenarios is crucial for effective React development.

TAGS
Coding Interview
CONTRIBUTOR
Arslan Ahmad
Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.
-

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Which software engineer has the highest salary?
Why do you choose Salesforce?
What are the tips for coding interviews at logistics companies?
What Is the Discord Interview Process Like? (Round by Round)
Discord's loop is anchored by its build-a-service round (the TCP chat server is real), with a full-day panel covering Values, Attitude, Coding, and Architecture. Structure and preparation.
What is coding in computer networks?
What is a third stage interview?
Related Courses
New
Grokking the AI System Design Interview course cover
Grokking the AI System Design Interview
Learn to design AI systems the way interviewers expect: classic ML products, LLM and RAG architectures, and agentic systems, all through the lens of the system design interview.
4.8
(1,192 learners)
Discounted price for Your Region

$123

Grokking the Coding Interview: Patterns for Coding Questions course cover
Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
4.1
Discounted price for Your Region

$72

Design Gurus logo
One-Stop Portal For Tech Interviews.
Copyright © 2026 Design Gurus, LLC. All rights reserved.