Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to change the state of react component on click?
Next article icon

How to update the state of react components using callback?

Last Updated : 12 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 :


Next Article
How to change the state of react component on click?
author
hunter__js
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • ReactJS

Similar Reads

  • How to update the State of a component in ReactJS ?
    To display the latest or updated information, and content on the UI after any User interaction or data fetch from the API, we have to update the state of the component. This change in the state makes the UI re-render with the updated content. Prerequisites: NPM & Node.jsReact JSReact StateReact
    3 min read
  • How to change the state of react component on click?
    To change the state of the React component is useful when you are working on a single page application, it simply replaces the content of the existing component for the user without reloading the webpage. We have to set initial state value inside constructor function and set click event handler of t
    2 min read
  • How to wait for a ReactJS component to finish updating ?
    To wait for a ReactJS component to finish updating, we use a loading state in our react application by use of the conditional rendering of the component. ApproachThis can be achieved by the use of the useState and useEffect hooks in the functional components. With the help of the state, we make sure
    3 min read
  • How to set up the Provider Component in a React application ?
    In React applications, the Provider component is often used in conjunction with context to provide data to components deep down in the component tree without having to explicitly pass props through every level of the tree. Prerequisites:JavaScriptReactNode & NPMSteps to Create React Application:
    3 min read
  • Using setTimeouts in React Components
    The setTimeout method in React enables the execution of a function after a specified time interval. This functionality is pivotal in web development for implementing time-based behaviors, offering a spectrum of applications ranging from user interface enhancements to asynchronous operations. The set
    6 min read
  • How to add a CSS class whenever the component is updated in React JS ?
    In this article, we will learn how to add a CSS class conditionally in React JS. If we want to update/add a CSS class when the component is updated or the state/props of components change then we have to conditionally apply the CSS based on the state/props value.  Syntax of adding CSS classes condit
    2 min read
  • How to share state across React Components with context ?
    The React Context Provides simple and efficient way to share state across the React components. In this article, we will see how to share state across React Components with Contect API. Prerequisites:React Context React useState HookApproachTo share state across React Components with Context we will
    4 min read
  • How to add Stateful component without constructor class in React?
    Generally, we set the initial state of the component inside the constructor class and change the state using the setState method. In React basically, we write HTML-looking code called JSX. JSX is not a valid JavaScript code but to make the developer's life easier BABEL takes all the responsibility t
    2 min read
  • How to connect the components using Connect() in React Redux
    In React Redux, you use the connect() function to connect your components to the Redux store. This function takes two parameters: mapStateToProps and mapDispatchToProps. mapStateToProps maps the store's state to the component's props, while mapDispatchToProps maps dispatch actions to props. By using
    3 min read
  • How to Map Data into Components using ReactJS?
    Mapping data in react js component is a comman practice to render the lists and repeating elements. In this article, we will have a users data and we will map it to react components to display the users information in the react app Prerequisites:React JSNodejs and npmJavaScript Array mapApproachTo m
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences