setState is a method used in React class components to update the component’s state that triggers a re-render with the updated values. All the React components can have a state associated with them. The state of a component can change either due to a response to an action performed by the user or an event triggered by the system.
We use the setState() method to change the state object. It ensures that the component has been updated and calls for re-rendering of the component.
React JS setState
setState in React is an asynchronous call means if a synchronous call gets called it may not get updated at the right time like to know the current value of an object after an update using setState it may not give the updated value on the console. To get some behavior for synchronous need to pass function instead of object to setState.
To deepen your knowledge of state management and other advanced React concepts, consider enrolling in the React JS Course offered by GeeksforGeeks. This course provides a comprehensive overview of state management techniques, including hooks like useState and useReducer, allowing you to manage state more effectively in functional components. With hands-on projects and practical applications, you’ll gain the skills necessary to build robust React applications.
Syntax:
We can use setState() to change the state of the component directly as well as through an arrow function.
setState({ stateName : updatedStateValue })
// OR
setState((prevState) => ({
stateName: prevState.stateName + 1
}))Steps to Create React Application
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project structure:

Approach 1: Updating single attribute
We set up our initial state value inside constructor function and create another function updateState() for updating the state. Now when we click on the button, the latter gets triggered as an onClick event which changes the state value. We perform setState() method in our updateState() function by writing:
this.setState({
greeting : 'GeeksForGeeks welcomes you !!'
}) As you can see, we are passing an object to setState(). This object contains the part of the state we want to update which, in this case, is the value of greeting. React takes this value and merges it into the object that needs it. It’s just like the button component asks what it should use for updating the value of greeting and setState() responds with an answer.
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;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Approach 2: Updating multiple attributes
The state object of a component may contain multiple attributes and React allows using setState() function to update only a subset of those attributes as well as using multiple setState() methods to update each attribute value independently.
We set our initial state by initializing three different attributes, and then we create a function updateState() which updates its value whenever it is called. Once again this function gets triggered as an onClick event and we get the updated values of our states at the same time.
JavaScript
// Filename - App.js
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
// Set initial state
this.state = {
test: "Nil",
questions: "0",
students: "0",
};
// Binding this keyword
this.updateState = this.updateState.bind(this);
}
updateState() {
// Changing state
this.setState({
test: "Programming Quiz",
questions: "10",
students: "30",
});
}
render() {
return (
<div>
<h2>Test Portal</h2>
<p>{this.state.test}</p>
<p>{this.state.questions}</p>
<p>{this.state.students}</p>
{/* Set click handler */}
<button onClick={this.updateState}>
Click me!
</button>
</div>
);
}
}
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Approach 3: Updating state values using props
We set up an array of strings testTopics as props for our component. A function listOfTopics is created to map all the strings as list items in our state topics. The function updateState gets triggered and sets the topics to list items. When we click on the button, we get updated state values. This method is well-known for handling complex data and updating the state very easily.
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;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Approach 4: Updating the state using its previous value
We create an initial state count having a value of 0. The function updateState() increments the present value of the state by 1 whenever it is called. This time we use setState() method in an arrow function by passing prevState as a parameter. The current value of the state is accessed with prevState.stateName which gets incremented by 1 whenever we press the button. This method is really useful when we are setting a value in the state in such a way that it depends on its previous value. For example, toggling a boolean (true/false) or incrementing/decrementing a number.
JavaScript
// Filename - App.js
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
// Set initial state
this.state = {
count: 0,
};
// Binding this keyword
this.updateState = this.updateState.bind(this);
}
updateState() {
// Changing state
this.setState((prevState) => {
return { count: prevState.count + 1 };
});
}
render() {
return (
<div>
<h2>Click Counter</h2>
<p>
You have clicked me {this.state.count}{" "}
times.
</p>
{/* Set click handler */}
<button onClick={this.updateState}>
Click me!
</button>
</div>
);
}
}
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Summary
React setState provides a way to manage the state in React class components asynchronously and update the UI based on user interactions and other changes.
Similar Reads
ReactJS setState()
setState is a method used in React class components to update the component's state that triggers a re-render with the updated values. All the React components can have a state associated with them. The state of a component can change either due to a response to an action performed by the user or an
7 min read
ReactJS State
State is a fundamental concept in ReactJS that plays an important role in building interactive and dynamic web applications. In this article, we will dive deep into what state is in ReactJS, how to use it and explore advanced techniques for managing state in large applications. Table of Content What
4 min read
React useState Hook
useState Hook is used to access state in the React functional components. It is a special function that allows you to manage state within functional components without the need for class-based components. The useState hook is a powerful addition to React, introduced in version 16.8. In this useState
6 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 State vs Props
In React props are a way to pass the data or properties from parent component to child components while the state is the real-time data available to use within only that component. States and props are two of the most important concepts of React and everything in React is based upon them. But before
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 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
ReactJS useRef Hook
The useRef hook allows you to persist values between renders without triggering a re-render. Whether you're dealing with DOM manipulation, storing previous values, or managing timers, useRef is an efficient solution. Table of Content What is useRef hook?Reasons to use useRef hookImplementing the use
4 min read
State Hooks in React
State Hooks, introduced in React 16.8, revolutionized how developers manage state in functional components. Before State Hooks, state management was primarily confined to class components using the setState method. State Hooks, such as useState, enable functional components to manage local state eff
3 min read
Is setState() method async ?
The React setState is asynchronous method. It has the ability to manage and update component state. However, there remains some confusion and debate regarding whether the setState() method is asynchronous or not. In this article, we'll dive into this topic and shed light on how the setState() method
3 min read
Lifting State Up in ReactJS
In ReactJS, "lifting state up" is a fundamental concept that plays an important role in managing the state efficiently across different components. When building React applications, it is common for multiple components to need access to the same piece of data or state. In such cases, instead of dupl
4 min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs) and Virtual DOM for building web applications that are fast, efficient, and scalable. Applications are built using reusable compon
6 min read
ReactJS useId Hook
React useId Hook is introduced for the ReactJS versions above 18. This hook generates unique IDs i.e, returns a string that is stable across both the server and the client sides. Prerequisite: Introduction and installation of ReactJSReact Hooks Syntax: const id = useId() Creating React Application:
3 min read
ReactJS useLayoutEffect Hook
The React JS useLayoutEffect works similarly to useEffect but rather works asynchronously like the useEffect hook, it fires synchronously after all DOM loading is done loading. This is useful for synchronously re-rendering the DOM and also to read the layout from the DOM. But to prevent blocking the
2 min read
What is state in React?
In React, state refers to the data that represents the current condition or values of a component. The state allows React components to keep track of and manage dynamic information, such as user input, API responses, or changes in the component's internal state. Here are key points about the state o
2 min read
ReactJS Reactstrap Tab Component
Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Tab component allows the user to switch between components present in given different tabs. We can use the following approach in React
3 min read
ReactJs useDebugValue Hook
React useDebugValue Hook is introduced for the ReactJs versions above 18. React useDebugValue Hook helps developers debug custom hooks in React Developer Tools by adding additional information and labels to those hooks. Prerequisite:ReactJSReact Developer ToolsReact HooksReact Custom HooksApproach:T
2 min read