The Wayback Machine - https://web.archive.org/web/20241118181525/https://www.geeksforgeeks.org/what-is-the-second-argument-that-can-optionally-be-passed-to-setstate-and-what-is-its-purpose/
Open In App

What is the second argument that can optionally be passed to setState and what is its purpose ?

Last Updated : 02 Nov, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The second argument that can optionally be passed to setState is a callback function which gets called immediately after the setState is completed and the components get re-rendered. 

If you want your program to update the value of a state using setState and then perform certain actions on the updated value of the state then you must specify those actions in a function which should be the second argument of the setState. If we do not do so then those actions will be performed on the previous value of state because of the asynchronous nature of setState.

Prerequisites

Steps to create the React Application:

Step 1: Create a React application using the following command:

npx create-react-app setState_example

Step 2: After creating your project folder i.e. setState_example , move to it using the following command:

cd setState_example

Project Structure:

Example 1: This example calls setState without the second argument, so the component does not get updated.

Javascript




// Filename - App.js
 
import React, { Component } from "react";
 
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: "GFG",
        };
    }
 
    updateName = (value) => {
        console.log("Previous name: " + this.state.name);
        this.setState({ name: value });
        console.log("Current name: " + this.state.name);
    };
 
    render() {
        const { name } = this.state;
        return (
            <div>
                <p>Welcome To GFG</p>
 
                <input
                    type="text"
                    value={name}
                    onChange={(e) =>
                        this.updateName(e.target.value)
                    }
                />
            </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:

Output

Example 2: This example calls The callback function immediately after the value in the state is updated and hence the new value is displayed.

Javascript




// Filename - App.js
 
import React, { Component } from "react";
 
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            name: "GFG",
        };
    }
 
    updateName = (value) => {
        console.log("Previous name: " + this.state.name);
        this.setState({ name: value }, () => {
            // Passing it as a second parameter to setState
            console.log("Current name: " + this.state.name);
        });
    };
 
    render() {
        const { name } = this.state;
        return (
            <div>
                <p>Welcome To GFG</p>
 
                <input
                    type="text"
                    value={name}
                    onChange={(e) =>
                        this.updateName(e.target.value)
                    }
                />
            </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:

output



Similar Reads

What is the purpose of callback function as an argument of setState event ?
In React, the purpose of callback function as an argument of setState event is to execute the code after the data in the state is modified. Purpose of callback function as an argument of setStateSetState is an asynchronous method. Asynchronous means that the remaining code will get executed while the current action is being performed. Whereas synch
2 min read
Which is first argument typically passed to a Node.js callback handler ?
A callback handler function in Node.js is a way to handle something after a particular operation is completed. It is one of the ways to handle asynchronous code which takes a long time to yield the result so we can call the callback handler with the error if any, and the result of the asynchronous operation. The callback handler functions follow th
3 min read
How Typescript Is Optionally Statically Typed Language ?
In this article, we will explore statical typing in typescript and what makes the language optionally statically typed. TypeScript is a strongly typed programming language that builds on top of JavaScript. TypeScript allows specifying the types of data being passed around within the code and has the ability to report errors when the types don't mat
2 min read
What is the purpose of using super constructor with props argument in ReactJS ?
React, an open-source JavaScript library for UI design utilizes JSX to render components. Data is passed from parent to child components through props, which can only be updated by the parent. The `super()` function invokes the constructor of the parent class. Prerequisites:NodeJS or NPMReact JSReact PropsSteps to Create the React Application:Step
1 min read
How re-render a component without using setState() method in ReactJS ?
In React, to re-render a class-based component with an updated state we generally use the setState() method. But instead, we can use other methods to re-render a component without using setState(). Prerequisites: NPM & Node.jsReact JSReactJS propsReactJS forceUpdate() methodApproaches to re-render a component without using setState() method are
3 min read
Explain lifecycle of ReactJS due to all call to this.setState() function
In React, the states are used to store data for specific components. These states can be updated accordingly using this.setState function. Updating of state leads to the rendering of UI. Different lifecycle methods are called during these renderings. Lifecycle methods called when the app is loaded first: Constructor()render()componentDidMount()Life
2 min read
How to force ReactJS to re-render on every setState call ?
React components automatically re-render when state or props change. To force a re-render without changes, use the `forceUpdate()` method, bypassing the `shouldComponentUpdate()` lifecycle method. `shouldComponentUpdate()` enables components to exit the update lifecycle when unnecessary re-renders are to be avoided. Syntax: this.forceUpdate()Approa
2 min read
What's the difference between forceUpdate vs setState ?
The difference between forceUpdate() and setState() is i.e setState() re-render the component if some state or props of that component is changed. When we call setState() the lifecycle method shouldComponentUpdate() method calls automatically which decides if the component should re-render or not. The shouldComponentUpdate() method exits the update
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 behaves. Prerequisite:Callback and async-await in
3 min read
How to Update an Object with setState in ReactJS?
setState in React is used to update the component state. Updating an object with setState involves modifying only specified properties of object without modifying the complete object. Directly updating the object can lead to the loss of data and unwanted results. Prerequisites:ReactJSsetStateApproachTo update an object with setState in React we wil
2 min read
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 event triggered by the system. We use the setStat
7 min read
How to returns a passed string with letters in alphabetical order in JavaScript ?
Let's say we need to convert the string into alphabetical order. For example: geeksforgeeks -> eeeefggkkorss Approach: The task is to create a function that takes a string and returns the alphabetical order of that string. Hence to achieve this we will go under the split, sort, and join method in javascript. Step 1: Split the given string into c
2 min read
How to print command line arguments passed to the script in Node.js ?
Node.js is an open-source and cross-platform runtime environment built on Chrome's V8 engine that enables us to use JavaScript outside the browser. Node.js helps us to use build server-side applications using JavaScript. In Node.js if you want to print the command line arguments then we can access the argv property on the process object. process.ar
2 min read
How Parameters are Passed to Functions in JavaScript ?
In JavaScript, parameters are passed to functions in a couple of ways: by value and by reference. Passing by Value: When primitive data types (like numbers, strings, or booleans) are passed as parameters, they are passed by value. This means that the actual value of the variable is passed to the function. Example: Here, the value of x (which is 5)
2 min read
How to get removed elements of a given array until the passed function returns true in JavaScript ?
The arrays in JavaScript have many methods which make many operations easy. In this article let us see different ways how to get the removed elements before the passed function returns something. Let us take a sorted array and the task is to remove all the elements less than the limiter value passed to the function, we need to print all the removed
4 min read
How to check whether a passed string is palindrome or not in JavaScript?
We are given a string, our task is to find string is palindrome or not. A palindrome is a series of numbers, strings, or letters that, when read from right to left and left to right, match each other exactly or produce the same series of characters. in simple words when number strings or characters are inverted and still provide the same outcome as
4 min read
How to get the first non-null/undefined argument in JavaScript ?
There are many occasions when we get to find out the first non-null or non-undefined argument passed to a function. This is known as coalescing. Approach 1: We can implement coalescing in pre-ES6 JavaScript by looping through the arguments and checking which of the arguments is equal to NULL. We then return the argument that is not NULL immediately
5 min read
Variable-length argument list in PHP
Given a set of arguments whose length is unknown at present, we will see how a function can work with these unknown numbers of arguments whose quantity will vary depending on the requirement. We will take up each word one by one to deeply understand the topic we are dealing with. Variable: It is the number of arguments keep changing. Length: It ref
2 min read
JavaScript RangeError Argument is not a valid code point
This JavaScript exception Invalid code point occurs if NaN values, negative Integers, non-Integers, or other values larger than 0x10FFFF are used with the String.fromCodePoint() method. Output: RangeError: {0} is not a valid code point (Firefox) RangeError: Invalid code point {0} (Chromium) Error Type: RangeError Cause of the error: The String.from
2 min read
JavaScript SyntaxError - Missing ) after argument list
This JavaScript exception missing ) after argument list occurs if there is an error in function calls. This could be a typing mistake, a missing operator, or an unescaped string. Message: SyntaxError: Expected ')' (Edge) SyntaxError: missing ) after argument list (Firefox) Error Type: SyntaxError Cause of Error: Somewhere in the code, there is an e
1 min read
JavaScript TypeError - Variable "x" redeclares argument
This JavaScript exception variable redeclares argument occurs in strict-mode only and if the variable name which is also function parameter has been redeclared with the var keyword. Message: TypeError: variable "x" redeclares argument (Firefox) Error Type: TypeError Cause of the Error: A variable which is the parameter of the function has been re-d
1 min read
JavaScript TypeError - Invalid Array.prototype.sort argument
This JavaScript exception invalid Array.prototype.sort argument occurs if the parameter of Array.prototype.sort() is not from either undefined or a function which sorts accordingly. Message: TypeError: argument is not a function object (Edge) TypeError: invalid Array.prototype.sort argument (Firefox) Error Type: TypeError Cause of the Error: The ar
1 min read
Explain the use of splats with tailing argument in CoffeeScript
CoffeeScript is a lightweight language that compiles into JavaScript. It provides simple and easy-to-learn syntax avoiding the complex syntax of JavaScript. CoffeeScript is influenced by JavaScript, Ruby, YAML, Haskell, Perl, Python and has influenced MoonScript, LiveScript, and JavaScript. Installation of CoffeeScript: Install locally for a projec
3 min read
What happens if you do not use rest parameter as a last argument ?
The rest parameter (...) was introduced in ES6 to allow functions to accept an indefinite number of arguments, irrespective of how they are defined. This is useful when the number of parameters passed in a function call is not fixed. Syntax: function f(arg1, arg2, arg3, ...arg4){ // body } arg4 is the array formed using the rest parameter as define
2 min read
How to get Argument Types from Function in TypeScript ?
In TypeScript, the Parameters utility type allows you to extract the types of a function's parameters. This is particularly useful when you want to work with the types of arguments dynamically, enabling functions that operate on any function's parameter types. In this article, we are going to see how to get argument types from functions in Typescri
2 min read
How to Type Dynamic Object with Methods with Dynamic Argument Count ?
We are going to learn about how to type dynamic objects with methods with dynamic argument count. Type dynamic object with methods with dynamic argument count means defining an object in a programming language such as TypeScript or Python, where the methods of the object can accept varying numbers of arguments dynamically at runtime, providing flex
2 min read
When rendering a list and what is a key and it's purpose ?
Whenever we render a list in React using the map method which is mostly preferred, we need to provide the keys. If we do not provide a key during rendering we get a warning in our react application. To remove that warning and optimize our code we provide a key. Prerequisites:Node JS or NPMReact JSKeys are something that helps react to identify whic
2 min read
Explain the purpose of the BrowserRouter and Route components.
React Router proves to be a robust library that empowers client-side routing in React applications. At its core, two pivotal components, BrowserRouter and Route, play key roles. In this article, we'll explore into the functions and application of these components, providing insights into how they streamline navigation and routing within your React
5 min read
API documentation in Postman: Purpose and Benefits
Postman is an API(utility programming interface) development device that enables to construct, take a look at and alter APIs. It could make numerous varieties of HTTP requests(GET, POST, PUT, PATCH), store environments for later use, and convert the API to code for various languages(like JavaScript, and Python). Purpose1. Clarity and Understanding:
4 min read
What is the purpose of self executing function in JavaScript?
The self-executing anonymous function is a special function which is invoked right after it is defined. There is no need to call this function anywhere in the script. This type of function has no name and hence it is called an anonymous function. The function has a trailing set of parenthesis. The parameters for this function could be passed in the
3 min read
three90RightbarBannerImg