- React Tutorial
- React Home
- React Setup
- React Introduction
- React ES6
- React Render HTML
- React JSX
- React Components
- React Class
- React Props
- React Events
- React Conditional
- React Lists
- React Forms
- React Router
- React Memo
- React CSS Styling
- React Hooks
- What is a Hook?
- React useState
- React useEffect
- React useContext
- React useRef
- React useReducer
- React useCallback
- React useMemo
- React Custom Hooks
React useState Hook
- useState is the most fundamental React Hook. It allows you to add "state" to functional components, which is essentially memory that React uses to track data that changes over time.
Developer Tip: Think of state as the "data of the moment." If a piece of data changes and you want the user interface to update automatically to reflect that change, it belongs in state.
Purpose
- Before Hooks, functional components were "stateless"—they could only receive props. useState bridges this gap, giving functional components the power to manage their own local data.
- It triggers a re-render. When you update a state variable, React detects the change, calculates what’s different, and updates the DOM to keep the UI in sync with your data.
Best Practice: Don't use state for values that can be calculated from props or other state variables. Keeping your state "lean" prevents bugs and unnecessary re-renders.
Syntax
- You must import useState from the React package at the top of your file.
- The function takes one argument: the initial state. It returns an array with exactly two elements: the current value and a function to update it.
import React, { useState } from 'react';
const ExampleComponent = () => {
// We use array destructuring to name these two elements
const [state, setState] = useState(initialValue);
// state: The current value stored in memory
// setState: A function we call to change that value
};
Common Mistake: Trying to update the state variable directly (e.g.,
state = 'new value'). React won't know the data changed, and the UI won't update. Always use the setter function.
Usage
- Initializing state is simple: pass a number, string, boolean, or even an object into
useState(). - When the setter function is called, React schedules a re-render of the component with the new value.
import React, { useState } from 'react';
const Counter = () => {
// Initialize 'count' at 0
const [count, setCount] = useState(0);
const increment = () => {
// This updates the value and tells React to refresh the UI
setCount(count + 1);
};
return (
<div>
<p>Current Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
Developer Tip: You can name the state variables anything you like, but the industry standard is
[value, setValue].
Handling Complex State
- When managing objects or arrays, remember that useState does not automatically "merge" updates like the old Class-based
this.setStatedid. - You must spread the existing state into the new value to avoid losing other properties.
const [user, setUser] = useState({ name: 'Vikash', age: 25 });
// Updating just the age while keeping the name
const birthday = () => {
setUser(prevUser => ({
...prevUser,
age: prevUser.age + 1
}));
};
Watch Out: If you forget the
...prevUser spread operator, your state will be overwritten entirely, and the name property will disappear!
Functional Updates
- Sometimes, your new state depends on exactly what the previous state was (like a counter or a toggle). In these cases, pass a function to
setCountinstead of a raw value. - This ensures that even if multiple updates happen quickly, they all use the most up-to-date version of the state.
const [count, setCount] = useState(0);
// The 'prevCount' argument is guaranteed to be the most recent value
const increment = () => {
setCount(prevCount => prevCount + 1);
};
Best Practice: Always use the functional update pattern (
prev => next) when the new state is calculated using the old state. It prevents race conditions in complex apps.
Multiple State Variables
- You aren't limited to one
useStatecall. You can use it as many times as you need to keep your logic organized. - It is often better to separate unrelated data into their own state hooks rather than bundling everything into one giant object.
const [name, setName] = useState('Vikash');
const [age, setAge] = useState(25);
const [isLoggedIn, setIsLoggedIn] = useState(false);
Developer Tip: If you find yourself managing 5 or 6 different pieces of state that are closely related, consider using the
useReducer hook for cleaner code.
Summary
The useState hook is the foundation of interactivity in React. By mastering how to initialize, update, and manage both simple and complex data structures, you gain the ability to build dynamic, responsive user interfaces that react instantly to user input.