setState() for State in ReactJS

      • We have seen what exactly a State is in ReactJS, how to initialize state data and update it.
      • setState() causes a component to re-render.
      • Before moving further, be aware of this that setState() function in ReactJS works in ASYNCHRONOUS fashion. That is, when we update state values, they are not immediately available for use.
      • Do not modify state directly, Use setState()
    this.state.value='Text'; is wrong. You can only use this in constructor
    this.setState({value: 'Text'}); is right
    • In this article, we will see ways to update state data.
    • There are two ways to update state data
      • Object based
      • Function based: We use Arrow Functions for this approch
index.js

Create a new application. Delete all files from src folder except index.js.
Below is the code that demonstrate both the approaches. Replace the code in index.js file with the below code.

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = { 
            funstr: 'Functional Original text!' , 
            objstr: 'ObjectBased Original String' 
        };
    }

    clickMeFA = () => {
        console.log('Functional based approach');
        console.log(this.state.funstr);
        this.setState(() => ({ 
            funstr: 'Functional Updated Text' 
            }),() => {
                console.log(this.state.funstr);
            });
    }

    clickMeOBA = () => {
        console.log('Object based approach');
        console.log(this.state.objstr);
        this.setState({ objstr: 'ObjectBased Updated Text' });
        console.log(this.state.objstr);
    }

    render() {
        return (
            <div>
                <button onClick={this.clickMeOBA}>Click Me     Objectbased</button>
                <button onClick={this.clickMeFA}>Click Me FuncBased</button>
            </div>
        );
    }
}

ReactDOM.render(<App />, document.getElementById('root'));

Below is the output of above code

Related Article

Event Handling in ReactJS: This article have another example related to setState()

Unknown's avatar

Author: Akanksha Gupta

I am a developer and working on SharePoint and Project Server in an MNC. I have more than 10 years of experience in the same field.

One thought on “setState() for State in ReactJS”

Leave a comment

Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started