How to update the state of react components using callback? - GeeksforGeeks

12 Sep, 2021
The state is mutable in react components. To make the React applications interactive we almost use state in every react component. The state is initialized with some value and based on user interaction with the application we update the state of the component at some point in time using setState method. setState method allows to change of the state of the component directly using JavaScript object where keys are the name of the state and values are the updated value of that state. Often we update the state of the component based on its previous state. In these cases it is always advised to update the state using a callback-based approach because using this approach, it is ensured that previously states are fully updated and now we update the state based on its previously updated value. It is community advisable to use a callback-based approach to update the state using setState because it solves lots of bugs upfront that may occur in the future.
Syntax
this.setState(st => {
  return(
    st.stateName1 = state1UpdatedValue,
    st.stateName2 = state2UpdatedValue
  )
})
Example 1: This Example illustrates how to update state using a callback-based approach
index.js :
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
app.js :
Javascript
import React, { Component } from 'react' class App extends Component{  constructor(props){    super(props)    // initialize count state    this.state = {count : 0}    // bind this    this.handleClick = this.handleClick.bind(this)  }   // function to run after click  handleClick(){    // changing state using callback    this.setState(st => {      // count is incremented +1 time      // based on its previous value      return st.count += 1    })  }   render(){    return(      <div>        <h3>Number : {this.state.count}</h3>        <button onClick={this.handleClick}>            Increment count        </button>      </div>           )  }}export default App
Output :
Example 2:
index.js :
Javascript
import React from 'react'import ReactDOM from 'react-dom'import App from './App' ReactDOM.render(<App />, document.querySelector('#root'))
app.js :
Javascript
import React, { Component } from 'react' class App extends Component{  static defaultProps = {    name : ['John', 'Alex', 'Bob']  }  constructor(props){    super(props)         // initialize count state    this.state = {msg : 'Hi There', count:0}    // bind this    this.handleClick = this.handleClick.bind(this)  }   // function to run after click  handleClick(){    // changing state using callback    this.setState(st => {      return(        st.msg = `${st.msg}, ${this.props.name[st.count]}`,        st.count += 1      )      })  }   render(){    return(      <div>        <h3>Greetings!</h3>          <p>{this.state.msg}</p>          <button onClick={this.handleClick}>           Say greeting to employees!        </button>      </div>           )  }}export default App
Output :
surindertarika1234
react-js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Set the value of an input field in JavaScript
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?