Q:

In react class component why is the state not being changed in the first instance of button click? But in the second instance it gets updated?

In the below code when I click the button for the first time it prints the original state values even though the state is changed using setState(). But when I click the button for the second time it prints the new state values
import React, {Component} from 'react';

class App extends Component{
  state = {
    name:'Aneesh',
    age: '30'
  }

  handleClick= (event)=>{
    //this prints the original state
    console.log(this.state);
    this.setState({
      name:'Rayancha'
    })
    //This prints the original state in the first click and prints the new state after the second click
    console.log(this.state);
  }

  render(){
    return (
      <div>
        <h1>I am app component</h1>
        <p>My name is: {this.state.name} and my Age is {this.state.age}</p>
        <button onClick={this.handleClick}>Click Me</button>
      </div>
    )
  }
}

export default App;

A:

Your code actually is updating correctly. The problem is executing console.log(this.state) directly after calling this.setState(). You see, this.setState() is asynchronous, which means when you call it, there's nothing to stop code that is written after it from running immediately. Simply put, console.log() runs before state has finished updating.
As proof that your state actually updated, you can run a console.log() inside render. Since, a component will re-render every time you update state, you will be printing the new state value.
import React, {Component} from 'react';

class App extends Component{
  state = {
    name:'Aneesh',
    age: '30'
  }

  handleClick= (event)=>{
    //this prints the original state
    console.log(this.state);
    this.setState({
      name:'Rayancha'
    })
    //This prints the original state in the first click and prints the new state after the second click
    console.log(this.state);
  }

  render(){
    console.log(this.state.name)
    return (
      <div>
        <h1>I am app component</h1>
        <p>My name is: {this.state.name} and my Age is {this.state.age}</p>
        <button onClick={this.handleClick}>Click Me</button>
      </div>
    )
  }
}

export default App;

