Skip to content
Related Articles

Related Articles

How to update the state of react components using callback?
  • Last Updated : 15 Sep, 2020

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}>
                Incremment 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 :

react-js-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :