In React, setState() is an essential method used to update the state of a component, triggering a re-render of the component and updating the UI. This method allows React to efficiently manage and render changes in the component’s state.
What is setState()?
setState() is a method used to update the state in a React component. When you call this method, React schedules an update to the state and triggers a re-render of the component. The key advantage of using setState() is that it is declarative. Instead of manually manipulating the DOM, you simply inform React of the changes to state, and React handles the rendering for you.
Syntax
this.setState(updater, callback);
- updater: An object or a function that represents the changes to be applied to the component’s state.
- callback (optional): A function that is executed once the state has been updated and the component has re-rendered.
Key Points About setState()
- State is Immutable: Direct modification of state is not allowed in React. Instead, you use
setState()
to change it. - Triggers Re-render: When
setState()
is called, React schedules a re-render of the component to reflect the updated state. - Merging State: React merges the object passed to
setState()
with the current state. If the new state has a key already present in the old state, it updates the value. If not, it adds a new key-value pair. - Asynchronous:
setState()
is asynchronous. The state update doesn’t happen immediately but is scheduled, and React will update the component at an optimal time.
How Does setState() Work?
- Triggers Re-render: When setState() is called, React schedules an update to the component’s state and triggers a re-render. The updated state is reflected in the component’s output.
- Merging States: setState() merges the new state with the current state. This is especially useful when you only want to update part of the state, leaving other properties intact.
- Asynchronous Updates: setState() updates the state asynchronously, meaning the changes don’t happen immediately. React batches the updates for performance reasons, and the re-render will happen once all the updates have been processed.
Example Usage of setState()
Incrementing a Counter
JavaScript
import React, { Component } from 'react';
import './App.css';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
increment = () => {
this.setState({
count: this.state.count + 1
});
};
render() {
return (
<div className="App">
<h1>React Counter</h1>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
Output

Using setState()
In this code
- setState() is called inside the increment method to update the count state when the button is clicked.
- This triggers a re-render, and the updated count is displayed on the UI.
State Merging in setState()
React automatically merges the state passed to setState() with the existing state. This means that when you update part of the state, React will retain the other parts of the state that weren’t changed.
JavaScript
import React, { Component } from 'react';
class StateMergingExample extends Component {
constructor(props) {
super(props);
this.state = {
user: {
name: 'Riya Khurana',
age: 30
},
loggedIn: false
};
}
updateUser = () => {
this.setState(prevState => ({
user: {
...prevState.user,
name: 'Sneha Attri'
}
}));
};
toggleLogin = () => {
this.setState({
loggedIn: true
});
};
render() {
return (
<div>
<h1>State Merging</h1>
<p>Name: {this.state.user.name}</p>
<p>Age: {this.state.user.age}</p>
<p>Logged In: {this.state.loggedIn ? 'Yes' : 'No'}</p>
<button onClick={this.updateUser}>Update Name</button>
<button onClick={this.toggleLogin}>Log In</button>
</div>
);
}
}
export default StateMergingExample;
Output

Using a Function for setState()
You can also pass a function to setState(), which is useful when the new state depends on the previous state. This function will receive the previous state and props as arguments and should return the updated state.
JavaScript
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
increment = () => {
this.setState((prevState) => ({
count: prevState.count + 1
}));
};
render() {
return (
<div>
<h1>Counter: {this.state.count}</h1>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
Output

Function for setState()
In this code
- When the “Increment” button is clicked, the increment method updates count using setState() with a function that ensures the update is based on the previous state (prevState). This prevents errors from using stale state values.
Updating Attributes
When updating state with setState(), you can modify the attributes of the current state, adding or changing values as needed.
JavaScript
// Filename - App.js
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
// Set initial state
this.state = {
greeting:
"Click the button to receive greetings",
};
// Binding this keyword
this.updateState = this.updateState.bind(this);
}
updateState() {
// Changing state
this.setState({
greeting: "GeeksForGeeks welcomes you !!",
});
}
render() {
return (
<div>
<h2>Greetings Portal</h2>
<p>{this.state.greeting}</p>
{/* Set click handler */}
<button onClick={this.updateState}>
Click me!
</button>
</div>
);
}
}
export default App;
Output

In this code
- Initial state: greeting is set to “Click the button to receive greetings”.
- Button click: Triggers updateState to change greeting to “GeeksForGeeks welcomes you !!”.
- Binding: updateState is bound in the constructor to ensure proper this context.
- Rendering: Displays the greeting message and a button that updates the message on click.
Updating state values using props
In React, props are used to pass data from a parent component to a child component. While props themselves are immutable (i.e., they cannot be changed by the child component), they can be used to update the state of the child component. This allows for dynamic, data-driven UIs where child components react to changes in the parent’s data.
JavaScript
// Filename - App.js
import React, { Component } from "react";
class App extends Component {
static defaultProps = {
testTopics: [
"React JS",
"Node JS",
"Compound components",
"Lifecycle Methods",
"Event Handlers",
"Router",
"React Hooks",
"Redux",
"Context",
],
};
constructor(props) {
super(props);
// Set initial state
this.state = {
testName: "React js Test",
topics: "",
};
// Binding this keyword
this.updateState = this.updateState.bind(this);
}
listOfTopics() {
return (
<ul>
{this.props.testTopics.map((topic) => (
<li>{topic}</li>
))}
</ul>
);
}
updateState() {
// Changing state
this.setState({
testName: "Test topics are:",
topics: this.listOfTopics(),
});
}
render() {
return (
<div>
<h2>Test Information</h2>
<p>{this.state.testName}</p>
<p>{this.state.topics}</p>
{/* Set click handler */}
<button onClick={this.updateState}>
Click me!
</button>
</div>
);
}
}
export default App;
Output

In this code
- defaultProps: testTopics contains a list of topics.
- State: Initially, testName is “React js Test” and topics is empty.
- updateState(): Updates testName and topics state, rendering the list of topics.
- listOfTopics(): Maps through testTopics and displays them in a list.
- Button: On click, updates the state to display the test topics.
setState() is Asynchronous
One of the most important things to understand about setState() is that it is asynchronous. When you call setState(), React doesn’t immediately update the state. Instead, it batches multiple state updates and processes them later in an optimal way.
However, React provides a callback function that you can pass to setState() to run code after the state has been updated and the component has re-rendered.
JavaScript
this.setState(
{ count: this.state.count + 1 },
() => {
console.log('State updated:', this.state.count);
}
);
Best Practices for Using setState()
- Use Functional setState() for Previous State: Use the function form when updating state based on the previous state.
- Avoid Direct State Modifications: Always use setState() for updates.
- Batch Updates: Minimize re-renders by batching state updates.
- Avoid Mutating State: Create new copies of state objects using spread operators.
- Use Callbacks: Utilize the callback to handle actions after state updates.
Conclusion
The setState() method in React is a fundamental part of how React components manage and update state. Understanding how it works, including state merging, the asynchronous nature of updates, and how to use functions for state updates, is crucial for building dynamic and efficient applications. By leveraging setState() properly, you can create responsive, interactive UIs that react to user interactions and data changes seamlessly.
Similar Reads
ReactJS State
In React, the state refers to an object that holds information about a component's current situation. This information can change over time, typically as a result of user actions or data fetching, and when state changes, React re-renders the component to reflect the updated UI. Whenever state change
4 min read
React useState Hook
The useState hook is a function that allows you to add state to a functional component. It is an alternative to the useReducer hook that is preferred when we require the basic update. useState Hooks are used to add the state variables in the components. For using the useState hook we have to import
5 min read
ReactJS useUndoState hook
The useUndoState hook is a custom hook provided by the Rooks package for React. It is similar to the useState hook in addition to undo functionality. Arguments: initialValue: It is of the type boolean that describes the initial value of the state. Its default value is false.Options: It is of the typ
2 min read
ReactJS Refs
ReactJS Refs are used to access and modify the DOM elements in the React Application. It creates a reference to the elements and uses it to modify them. Table of Content Creating refs in ReactAccessing Refs in ReactWhy useRef over createRef in Function Components?When to use refsWhen not to use refs
4 min read
ReactJS State vs Props
In React, State allows components to manage and update internal data dynamically, while Props enables data to be passed from a parent component to a child component. Understanding their differences and use cases is essential for developing efficient React applications. State in ReactState is a built
4 min read
React Native State
In React Native, for data that is going to change, we have to use state. You can think of it as a variable. It allows us to store data and also change it when we want. Whenever you define a state, you need to provide an initial value for it. After that, you can use setState function provided by Reac
3 min read
What is useState() in React ?
The useState() is a Hook that allows you to have state variables in functional components . so basically useState is the ability to encapsulate local state in a functional component. React has two types of components, one is class components which are ES6 classes that extend from React and the other
2 min read
ReactJS Props - Set 1
The react props refer to properties in react that are passed down from parent component to child to render the dynamic content. Till now we have worked with components using static data only. In this article, we will learn about react props and how we can pass information to a Component. What are Pr
5 min read
ReactJS Props - Set 2
In our previous article ReactJS Props - Set 1 we discussed props, passing and accessing props, passing props from one component to another, etc. In this article, we will continue our discussion on props. So, what if we want to pass some default information using props to our components? React allows
4 min read
ReactJS useSelect hook
The useSelect is a custom hook provided by the Rooks package for React. It is a list selection hook that helps select values from a list. Arguments: list: It is of the type array which describes the list of items for the selection. The default value is undefined.initialIndex -It is of the type numbe
2 min read