Understanding the useState Hook in React JS
Topic: Understanding the useState Hook
Technology: React JS, JavaScript, JSX, Functional Components
Learning Objective: Understand how the useState Hook stores component data, updates state, triggers re-renders, handles user interactions, and manages values such as numbers, strings, Boolean values, objects, and arrays.
1. Introduction to the useState Hook
The useState Hook is a built-in React function that allows functional components to store and manage state. State is information that a component remembers between renders. For example, a counter needs to remember its current number, a form needs to remember the values entered by a user, and a shopping cart needs to remember selected products.
When a state value changes through its setter function, React schedules a re-render so the component can display the updated information.
In modern React development, useState is commonly used for counters, forms, dropdowns, menus, tabs, checkboxes, product quantities, and other interactive interface elements.
Example of useState
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
Explanation: The counter begins at zero. When the user clicks the Increase button, setCount(count + 1) requests a state update. React then renders the component with the updated count.
2. What Is State in React?
State is data that belongs to a component and can change while the application is running. React remembers state values between renders, allowing a component to display updated information when users interact with it.
Examples of state
- Counter: Stores the current count.
- Form: Stores a user's name, email, or password field value.
- Toggle: Stores whether a feature is enabled or disabled.
- Shopping cart: Stores selected products or quantities.
- Navigation menu: Stores whether a menu is open or closed.
- Tabs: Stores the currently selected tab.
- Search: Stores the text entered into a search field.
Why do we need state?
Ordinary local variables do not preserve their updated values between React renders and changing them does not itself tell React to update the screen. State solves both problems: React remembers the value and schedules a re-render when the setter requests a change.
function Example() {
let count = 0;
function increase() {
count = count + 1;
}
return (
<button onClick={increase}>
Count: {count}
</button>
);
}
Problem: Updating the local variable does not trigger a React re-render, so the displayed count will not update as expected.
Correct approach: Use useState when the value must be remembered and reflected in the user interface.
3. Syntax of the useState Hook
The basic syntax of the useState Hook is:
const [state, setState] = useState(initialState);
The Hook returns an array containing two values: the current state and a setter function. Array destructuring assigns these values to readable variable names.
Understanding each part
useState: React Hook used to declare a state variable.
initialState: The value used to initialize the state on the component's first render.
state: The current state value for the render being executed.
setState: The function used to request a state update.
const: Declares the local variable bindings returned by the Hook. React supplies the updated state on a subsequent render; you do not assign directly to the state variable.
Example
import { useState } from 'react';
function Welcome() {
const [name, setName] = useState('Manish');
return (
<div>
<h2>Welcome, {name}!</h2>
<button onClick={() => setName('Rahul')}>
Change Name
</button>
</div>
);
}
export default Welcome;
Initially, the component displays “Welcome, Manish!”. After clicking the button, React receives the new state value and displays “Welcome, Rahul!”.
4. Importing useState from React
Before using the named Hook in a React component, import it from React.
import { useState } from 'react';
You can then declare state inside a function component:
import { useState } from 'react';
function App() {
const [message, setMessage] = useState('Hello React');
return (
<div>
<p>{message}</p>
<button onClick={() => setMessage('Welcome to React JS')}>
Update Message
</button>
</div>
);
}
export default App;
The import makes the Hook available to the component. The component uses it to retain the message and update the displayed text.
5. How the useState Hook Works
The useState Hook works with React's rendering process. The component reads the current state during a render, and the setter function requests that the state be changed.
- Initial render: React initializes the state using the supplied initial value.
- State declaration: The component receives the current state and its setter function.
- User interaction: A user clicks a button, types into an input, or performs another action.
- State update request: The event handler calls the setter function with a new value or updater function.
- Re-render: React renders the component again when required and supplies the updated state value.
- UI update: React updates the relevant parts of the displayed interface.
Example: Updating a counter
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Current Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Add One
</button>
</div>
);
}
export default Counter;
Initial state: 0
After one click: 1
After two clicks: 2
After three clicks: 3
Each click requests an update based on the current count, and React displays the new value after rendering.
6. State Variable and Setter Function
Every useState declaration provides a state value and a setter function. A common naming convention is to name the state variable after the information it stores and prefix the setter with set.
| State Variable |
Setter Function |
Purpose |
count |
setCount |
Stores and updates a number. |
name |
setName |
Stores and updates a name. |
isOpen |
setIsOpen |
Stores whether a menu is open. |
email |
setEmail |
Stores an email input value. |
items |
setItems |
Stores and updates an array. |
user |
setUser |
Stores and updates an object. |
Important rule
Do not change a state variable directly. Use its setter function to request an update.
// Incorrect
count = count + 1;
// Correct
setCount(count + 1);
7. Different Data Types Supported by useState
The initial state can contain values of different JavaScript data types. Choose a type that represents the information your component needs to remember.
7.1 Number State
Number state is useful for counters, quantities, scores, and pagination.
import { useState } from 'react';
function Score() {
const [score, setScore] = useState(0);
return (
<div>
<h2>Score: {score}</h2>
<button onClick={() => setScore(score + 10)}>
Add 10 Points
</button>
</div>
);
}
export default Score;
7.2 String State
String state stores text, messages, names, titles, and user input.
import { useState } from 'react';
function Greeting() {
const [name, setName] = useState('Guest');
return (
<div>
<h2>Hello, {name}</h2>
<button onClick={() => setName('Student')}>
Change Greeting
</button>
</div>
);
}
export default Greeting;
7.3 Boolean State
Boolean state stores either true or false. It is useful for toggles, visibility, and status indicators.
import { useState } from 'react';
function ToggleMessage() {
const [isVisible, setIsVisible] = useState(false);
return (
<div>
<button onClick={() => setIsVisible(!isVisible)}>
Toggle Message
</button>
{isVisible && <p>Hello, React learner!</p>}
</div>
);
}
export default ToggleMessage;
7.4 Array State
Array state is useful for lists of tasks, products, names, and notifications. Create a new array when updating it instead of modifying the existing array.
import { useState } from 'react';
function FruitList() {
const [fruits, setFruits] = useState(['Apple', 'Banana']);
function addFruit() {
setFruits(previousFruits => [...previousFruits, 'Mango']);
}
return (
<div>
<ul>
{fruits.map((fruit, index) => (
<li key={`${fruit}-${index}`}>{fruit}</li>
))}
</ul>
<button onClick={addFruit}>Add Mango</button>
</div>
);
}
export default FruitList;
7.5 Object State
Object state is useful when multiple related properties belong together, such as a user's name and email.
import { useState } from 'react';
function UserProfile() {
const [user, setUser] = useState({
name: 'Amit',
city: 'Mumbai'
});
function changeCity() {
setUser(previousUser => ({
...previousUser,
city: 'Pune'
}));
}
return (
<div>
<p>Name: {user.name}</p>
<p>City: {user.city}</p>
<button onClick={changeCity}>Change City</button>
</div>
);
}
export default UserProfile;
8. Using Multiple useState Hooks
A component can declare more than one state variable. Use separate useState calls when the values represent independent pieces of information.
import { useState } from 'react';
function StudentProfile() {
const [name, setName] = useState('Aarav');
const [age, setAge] = useState(20);
const [isEnrolled, setIsEnrolled] = useState(true);
return (
<div>
<h2>Student Profile</h2>
<p>Name: {name}</p>
<p>Age: {age}</p>
<p>Enrolled: {isEnrolled ? 'Yes' : 'No'}</p>
<button onClick={() => setName('Riya')}>Change Name</button>
<button onClick={() => setAge(age + 1)}>Increase Age</button>
<button onClick={() => setIsEnrolled(!isEnrolled)}>
Toggle Enrollment
</button>
</div>
);
}
export default StudentProfile;
Each state variable has its own setter. Updating the name does not automatically change the age or enrollment status.
9. Updating State with a Setter Function
The setter function can receive either a new state value or a function that calculates the next state from the previous state.
9.1 Passing a new value
const [name, setName] = useState('Guest');
function updateName() {
setName('Manish');
}
Use this approach when the next value is already known or does not need to be calculated from the previous state.
9.2 Using an updater function
const [count, setCount] = useState(0);
function increaseCount() {
setCount(previousCount => previousCount + 1);
}
The updater function receives the pending previous state and returns the next state. This is useful when the next value depends on the previous value.
9.3 Multiple updates in one event
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
function increaseThreeTimes() {
setCount(previousCount => previousCount + 1);
setCount(previousCount => previousCount + 1);
setCount(previousCount => previousCount + 1);
}
return (
<div>
<p>Count: {count}</p>
<button onClick={increaseThreeTimes}>Increase by 3</button>
</div>
);
}
export default Counter;
Each updater calculates from the result of the preceding queued update, so clicking the button increases the count by three.
10. Understanding Re-rendering in React
A re-render means React runs a component again to determine what its user interface should display. When a state setter requests a different state value, React can re-render the component so the screen reflects the new state.
Example
import { useState } from 'react';
function LikeButton() {
const [likes, setLikes] = useState(0);
return (
<div>
<h2>Likes: {likes}</h2>
<button onClick={() => setLikes(likes + 1)}>
Like
</button>
</div>
);
}
export default LikeButton;
When the button is clicked, React updates the state and renders the current like count. React may batch multiple state updates, and requesting the same state value may not produce a visible re-render.
Important concept: state is a render snapshot
The state variable inside an event handler represents the value for the render in which that handler was created. Calling a setter does not change that variable immediately in the already-running code.
function handleClick() {
setCount(count + 1);
console.log(count); // Value from the current render
}
To use the next state in calculations, consider an updater function. If you need to run logic after a state-driven render or synchronize with an external system, choose an appropriate React pattern rather than expecting the setter to change the current variable immediately.
11. Using useState with Input Fields
The useState Hook is commonly used to control input fields in React forms. A controlled input receives its displayed value from state, and its change handler updates that state.
import { useState } from 'react';
function NameForm() {
const [name, setName] = useState('');
return (
<div>
<label htmlFor="studentName">Enter your name:</label>
<input
id="studentName"
type="text"
value={name}
onChange={event => setName(event.target.value)}
placeholder="Enter name"
/>
<p>Your name is: {name || 'Not entered'}</p>
</div>
);
}
export default NameForm;
How it works
- The input initially displays an empty string.
- The user types a character.
- The
onChange handler reads event.target.value.
- The setter stores the new string in state.
- React renders the updated input value and text.
For a controlled text input, initialize the state with a string such as '' and keep the value a string throughout the component's lifetime.
12. Building a Toggle Button with useState
A toggle button switches a Boolean state between true and false. It can control a message, dropdown, menu, or other conditional interface element.
import { useState } from 'react';
function ToggleButton() {
const [isOn, setIsOn] = useState(false);
return (
<div>
<h2>Status: {isOn ? 'ON' : 'OFF'}</h2>
<button onClick={() => setIsOn(previousValue => !previousValue)}>
Turn {isOn ? 'Off' : 'On'}
</button>
</div>
);
}
export default ToggleButton;
The updater reverses the previous Boolean value each time the button is clicked.
13. Updating Objects Correctly
React state should be treated as read-only. When an object stored in state needs to change, create a new object and preserve any properties that should remain unchanged.
Incorrect approach
user.name = 'Riya';
setUser(user);
This mutates the existing object instead of creating a new one. Passing the same object reference back can cause React to ignore the update.
Correct approach
setUser(previousUser => ({
...previousUser,
name: 'Riya'
}));
The spread operator copies the existing top-level properties, and the updated name replaces the old value. For nested objects, copy each level that needs to change.
14. Updating Arrays Correctly
Arrays stored in state should also be treated as read-only. Use array methods that return a new array, such as spread syntax, map(), filter(), and concat(), to create updated state.
Adding an item
setItems(previousItems => [...previousItems, newItem]);
Removing an item
setItems(previousItems =>
previousItems.filter(item => item.id !== itemId)
);
Updating an item
setItems(previousItems =>
previousItems.map(item =>
item.id === itemId
? { ...item, completed: true }
: item
)
);
These approaches create a new array and avoid directly modifying the existing state. When rendering a list, provide each item with a stable, unique key whenever possible.
15. Lazy Initialization with useState
Sometimes the initial state requires an expensive calculation. In that case, you can pass an initializer function to useState instead of calling the calculation directly.
Direct initialization
const [items, setItems] = useState(createInitialItems());
The expression createInitialItems() is evaluated whenever the component function runs, even though React uses the initial state only on the first render.
Lazy initialization
const [items, setItems] = useState(createInitialItems);
Here, React calls the initializer function to obtain the initial state when initializing the component. This can avoid repeating an expensive calculation on every render.
Important: Initializer functions should be pure. In development, React Strict Mode may call an initializer more than once to help detect accidental side effects.
16. Rules for Using the useState Hook
Follow the Rules of Hooks to make state behavior predictable.
- Call useState at the top level of a function component or a custom Hook.
- Do not call Hooks inside loops, conditions, nested functions, or event handlers.
- Call Hooks in the same order on every render.
- Do not call Hooks from ordinary JavaScript functions that are not React components or custom Hooks.
- Use the setter function to request a state update rather than assigning directly to the state variable.
- Treat objects and arrays in state as immutable.
- Keep updater and initializer functions pure: do not mutate existing state or perform unrelated side effects inside them.
- Do not call a setter unconditionally during rendering, because it can cause repeated rendering.
Incorrect conditional Hook usage
function Example({ show }) {
if (show) {
const [count, setCount] = useState(0);
}
return <div>Example</div>;
}
Correct Hook usage
function Example({ show }) {
const [count, setCount] = useState(0);
if (!show) {
return <div>Hidden</div>;
}
return <div>Count: {count}</div>;
}
In the correct example, the Hook is called before the conditional return, so its call order remains consistent.
17. Common Mistakes When Using useState
| Mistake |
Why It Is a Problem |
Correct Approach |
| Changing a state variable directly |
React does not receive a state update request. |
Call the corresponding setter function. |
| Mutating an object or array |
The existing reference may be unchanged, and React state should be treated as read-only. |
Create a new object or array. |
| Expecting state to change immediately |
The current render's variable remains a snapshot. |
Use the next render's state or an updater function where appropriate. |
| Using a stale value for repeated updates |
Multiple direct updates may calculate from the same render snapshot. |
Use a functional updater when each update depends on the previous one. |
| Calling Hooks conditionally |
Hook call order may change between renders. |
Call Hooks at the top level. |
| Calling a setter during every render |
Can create an infinite re-render loop. |
Update state in event handlers or other appropriate logic. |
| Using an unstable list key |
React may associate list items with the wrong component state. |
Use stable, unique item identifiers when available. |
| Storing values that can be calculated easily |
Redundant state can become inconsistent with the source data. |
Calculate derived values from existing props and state when appropriate. |
18. Practical Project: Counter Application Using useState
Project Objective: Create a counter that allows the user to increase, decrease, and reset the count. This exercise demonstrates state initialization, event handling, and updating state from the previous value.
Complete Code
import { useState } from 'react';
function CounterApp() {
const [count, setCount] = useState(0);
function increaseCount() {
setCount(previousCount => previousCount + 1);
}
function decreaseCount() {
setCount(previousCount => previousCount - 1);
}
function resetCount() {
setCount(0);
}
return (
<div>
<h1>Counter Application</h1>
<h2>Current Count: {count}</h2>
<button onClick={increaseCount}>Increase</button>
<button onClick={decreaseCount}>Decrease</button>
<button onClick={resetCount}>Reset</button>
</div>
);
}
export default CounterApp;
Project Explanation
useState(0) initializes the counter to zero.
increaseCount() requests an increment using the previous count.
decreaseCount() requests a decrement using the previous count.
resetCount() sets the count back to zero.
- The JSX displays the current count and provides three buttons.
Expected Output
Counter Application
Current Count: 0
[Increase] [Decrease] [Reset]
After clicking Increase twice, the count becomes 2. Clicking Decrease once makes it 1. Clicking Reset returns it to 0.
19. Practical Project: Simple To-Do List
Project Objective: Use the useState Hook to store a list of tasks, accept new task names, and add them to the displayed list.
import { useState } from 'react';
function TodoApp() {
const [task, setTask] = useState('');
const [tasks, setTasks] = useState([]);
function addTask() {
const trimmedTask = task.trim();
if (!trimmedTask) {
return;
}
setTasks(previousTasks => [
...previousTasks,
{
id: crypto.randomUUID(),
title: trimmedTask
}
]);
setTask('');
}
return (
<div>
<h1>To-Do List</h1>
<input
value={task}
onChange={event => setTask(event.target.value)}
placeholder="Enter a task"
/>
<button onClick={addTask}>Add Task</button>
<ul>
{tasks.map(item => (
<li key={item.id}>{item.title}</li>
))}
</ul>
</div>
);
}
export default TodoApp;
This project demonstrates string state, array state, controlled inputs, functional updates, and rendering lists. It uses crypto.randomUUID() to create task IDs in supported modern browser environments.
20. Advantages of the useState Hook
- Allows functional components to remember values between renders.
- Helps update the user interface in response to user interactions.
- Supports different JavaScript data types, including numbers, strings, Booleans, objects, and arrays.
- Works well with controlled form inputs.
- Enables reusable and readable component logic.
- Supports functional updater functions for calculations based on previous state.
- Helps build interactive features without requiring class components.
- Can be combined with other React Hooks when more advanced behavior is needed.
21. Limitations and Important Considerations
- State updates are scheduled by React; a setter does not immediately change the state variable in the current render.
- Complex state transitions may be easier to manage with
useReducer rather than many separate useState calls.
- State belongs to a particular component instance. To share state across components, you may need to lift state to a common parent or use context or another state-management approach.
- State updates must avoid direct mutation of objects and arrays.
- State is not automatically saved permanently when the page is refreshed. Persistent storage requires an appropriate mechanism, such as a backend or browser storage.
- Using state for values that can be calculated from existing props or state can introduce unnecessary complexity.
22. Difference Between useState and Ordinary Variables
| Feature |
Ordinary Variable |
useState |
| Stores a value during component execution |
Yes |
Yes |
| Preserves updated value across renders |
Not by itself |
Yes |
| Setter can request a re-render |
No |
Yes |
| Supports objects and arrays |
Yes |
Yes, with immutable update patterns |
| Suitable for interactive UI data |
Usually not on its own |
Yes |
23. Difference Between useState and useReducer
| Feature |
useState |
useReducer |
| Main purpose |
Manage a state value with a setter. |
Manage state through a reducer function and dispatched actions. |
| Best suited for |
Simple state and straightforward updates. |
More complex state transitions or related actions. |
| Update approach |
Call the setter with a value or updater function. |
Dispatch an action handled by the reducer. |
| Example use case |
Toggle, counter, input field. |
Complex form, multi-step workflow, task state transitions. |
24. Frequently Asked Interview Questions and Answers
Q1. What is the useState Hook in React?
Answer: useState is a built-in React Hook that allows a function component to store state and request updates to that state.
Q2. What does useState return?
Answer: It returns an array with two items: the current state value and a setter function used to request an update.
Q3. What is the purpose of the initial state?
Answer: The initial state provides the starting value when React initializes that state variable. The initial value is ignored on subsequent renders.
Q4. Can useState store a string or Boolean value?
Answer: Yes. It can store values of different types, including strings, numbers, Booleans, arrays, objects, and other JavaScript values.
Q5. Why should we not modify state directly?
Answer: React state should be treated as read-only. Direct mutation can cause incorrect behavior, and passing the same object or array reference may not trigger the expected update. Create a new object or array instead.
Q6. What happens when we call a state setter?
Answer: The setter requests a state update. React can then re-render the component using the updated state.
Q7. Does calling a setter immediately change the current state variable?
Answer: No. The variable remains the snapshot from the current render. The updated state is supplied during a subsequent render.
Q8. When should we use a functional updater?
Answer: Use a functional updater when the next state depends on the previous state, for example, setCount(previousCount => previousCount + 1).
Q9. Can a component use multiple useState Hooks?
Answer: Yes. A component can use multiple state variables for separate values, provided all Hook calls follow the Rules of Hooks.
Q10. Can useState manage form inputs?
Answer: Yes. A controlled input can use a state variable for its value and an onChange handler to update the value.
Q11. What is lazy initialization?
Answer: Lazy initialization means passing an initializer function, such as useState(createInitialItems), so React can call it to calculate the initial state instead of evaluating the calculation on every render.
Q12. What is the difference between state and props?
Answer: Props are values passed into a component by its parent, while state is information managed by the component or its owning state logic. Both can influence what the component displays.
25. Practice Exercises
- Create a counter that increases and decreases by one.
- Create a button that switches between Light Mode and Dark Mode labels.
- Create a text input that displays the entered name below the field.
- Create a checkbox that shows whether a user has accepted the terms.
- Create a list of five items and add a new item using a button.
- Create a shopping cart quantity control using number state.
- Create a form that stores a user's name, email, and city in object state.
- Create a to-do list that adds and removes tasks without mutating the array.
- Create a counter with an Increase by 5 button using a functional updater.
- Explain why directly changing an object stored in state is not recommended.
26. Quick Revision Checklist
- Understand what state means in React.
- Know how to import
useState from React.
- Understand the syntax
const [value, setValue] = useState(initialValue).
- Know the difference between the current state and the setter function.
- Understand how state updates can trigger re-renders.
- Know how to use state for numbers, strings, Booleans, objects, and arrays.
- Understand functional updater functions.
- Know how to create controlled input fields.
- Avoid direct mutation of objects and arrays.
- Follow the Rules of Hooks.
- Practice building counter, toggle, form, and to-do list components.
27. Official React Documentation
For further learning and examples, refer to the official React documentation:
28. React JS Training Course and Demo Registration
To learn React JS concepts, build practical projects, and strengthen your frontend development skills, explore the following JustAcademy resources.
React JS Training Course: JustAcademy React JS Training Course
Course Demo Registration: Register for React JS Course Demo
Conclusion
The useState Hook is one of the most important React Hooks because it enables function components to remember data and update their user interfaces in response to interactions. By understanding state initialization, setter functions, re-rendering, functional updates, controlled inputs, and immutable object and array updates, you can create interactive React applications more confidently.
Practice the counter, toggle, form, and to-do list examples to build a strong foundation before moving on to more advanced React topics.