setstate doesn't update the state immediately

  • Last Update :
  • Techknowledgy :

setState is asynchronous. It means you can’t call it on one line and assume the state has changed on the next. setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains. Since setSatate is a asynchronous function so you need to console the state as a callback like this.

This is our Splunktool team suggestion, we tried and its working fine ✌
this.setState({
   pencil: !this.state.pencil
}, myFunction)​

Your state needs some time to mutate, and since console.log(this.state.boardAddModalShow) executes before the state mutates, you get the previous value as output. So you need to write the console in the callback to the setState function

openAddBoardModal() {
   this.setState({
      boardAddModalShow: true
   }, function() {
      console.log(this.state.boardAddModalShow);
   });
}

Fortunately setState() takes a callback. And this is where we get updated state.

Consider this example.

this.setState({
   name: "myname"
}, () => {
   //callback
   console.log(this.state.name) // myname
});

Suggestion : 2

To update state in React components, we’ll use either the this.setState function or the updater function returned by the React.useState() Hook in class and function components, respectively. State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass. In this article, we’ll explore the reasons why React doesn’t update state immediately. We’ll run through an example and clarify what you should do when you need to make changes to the new state in both class and function components. Let’s get started!

For example, consider the code below:

//React
const handleClick = () => {
   setName("Amaka")
   setAge(20)
   setAddress("No 3 Rodeo drive")
}

The second parameter to setState() is an optional callback function. This argument will be executed once setState() is completed and the component is re-rendered. The callback function is guaranteed to run after the state update has been applied:

//React

handleSearch = (e) => {
   this.setState({
      searchTerm: e.target.value
   }, () => {
      // Do an API call with this.state.searchTerm
   });
}

The componentDidUpdate function is invoked immediately after a state update occurs. To avoid an infinite loop, you should always use a conditional statement to be sure that the previous state and the current state are not the same:

//React

componentDidUpdate(prevProps, prevState) {
   if (prevState.count !== this.state.count) {
      // Do something here
   }
}

Suggestion : 3

React this.setState, and useState does not make changes directly to the state object. React this.setState, and React.useState create queues for React core to update the state object of a React component. Let’s dive into why this.setState and React.useStatedo not update immediately. Does it feel like when you call this.setState or React.useState, the changes feel like it’s a step behind?

If you’re using a class component, you will have to usethis.setState() to update the state of a React component.

this.setState(state, callback);

The second parameter this.setState() accepts is the callback function, and that’s where you’ll want to add your side effects.

This callback function will get triggered when React state has finished updating.

this.setState(newStateObject, () => {
   // ... do some other actions
});

The example above uses the arrow function, but you can do it with a traditional function syntax.

this.setState(newStateObject, function() {
   // ... do some other actions
});

That hook function will only activate if the values in the list change.

Let’s take a look at an example

let s;

const Foo = () => {
  const [counter, setCounter] = React.useState(0);

  // Emmulate componentDidMount lifecycle
  React.useEffect(() => {
    s = setInterval(() => {
      setCounter(state => (state +1));
    }, 1000);
  }, []);

  // This is for counter state variable
  React.useEffect(() => {
    if (counter > 9) {
      clearInterval(s);
    }
  }, [counter]);

  return <span>{counter}</span>;
};

Suggestion : 4

The reason why the state doesn’t update immediately is because for each render, the state is immutable. Plenty of articles have been written about this saying setState is asynchronous. This may sounds probable but it isn’t the exact reason why your state doesn’t update immediately. …are both constants values ! So they’re immutable. The state remains constant inside the render but can be changed between two renders. The same goes for dispatch and useReducer. but this is actually normal, just as expected. The component has to rerender before updating the new state.

1._
function onClick() {
   //let's say last state was 1
   setSomeState(2)
   console.log(someState); //will log 1 but not 2
}
2._
function App(){

    const [count, setCount] = useState(1);

    function onClick(){
        setCount(count + 1)
        console.log(count);  
    // First time the button is clicked this will log 1, not 2
    // This console logged count will always "lag behind"
    }

    console.log(count) 
    //This will log 1 on first render 
    //before clicking the button.
    //After the first button click, the state 
    //will be updated which triggers a second 
    //render and then this will log 2

    return(
    <button onClick={onClick}>increment count</button>
    )
	
}
3._
function onClick() {
   await setCount(count + 1) //not possibile
   console.log(count); //logs 2
}
5._
//Instead of this:

function onChange() {
   setCount(count + 1);
   getData(count);
   //here count is not equal to the state 
   //you just set, it's the previous state
}

//Do this:
function onChange() {
   const newCount = count + 1;
   setCount(newCount);
   getData(newCount);
   //now you can be sure you call getData
   //with the state you just set
}
6._
useEffect(() => {
   getData(count);
}, [count])

Suggestion : 5

The method setState() takes a callback. And this is where we get updated state. So When callback fires, this.state is the updated state. You can get mutated/updated data in callback. Error setState doesn t update the state... Hello @kartik, In order to setState for a nested object ...READ MORE

 When I do an onclick event. I have search a while ago that I need to bind the onclick function in constructor but still the state is not updating. \

Here's my code:

import React from 'react';

import Grid from 'react-bootstrap/lib/Grid';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';

import BoardAddModal from 'components/board/BoardAddModal.jsx';

import style from 'styles/boarditem.css';

class BoardAdd extends React.Component {

    constructor(props){
        super(props);

        this.state = {
            boardAddModalShow: false
        }

        this.openAddBoardModal = this.openAddBoardModal.bind(this);
    }
    openAddBoardModal(){
        this.setState({ boardAddModalShow: true });
// After setting a new state it still return a false value
        console.log(this.state.boardAddModalShow);

    }

    render() {

        return (
            <Col lg={3}>
                <a href="javascript:;" className={style.boardItemAdd} onClick={this.openAddBoardModal}>
                    <div className={[style.boardItemContainer,style.boardItemGray].join(' ')}>
                        Create New Board
                    </div>

Consider this example.

this.setState({
      name: "Mustkeom"
   },
   () => { //callback
      console.log(this.state.name) // Mustkeom
   }
);

Suggestion : 6

State updates in React are not applied immediately. Instead, they are placed in a queue and scheduled. In fact, React does not apply the new values to the state until the component is reconciled. Moreover, React Fiber architecture introduced in React 16 may rearrange the component update queue, putting more important updates (like animation) ahead of less important. All that means that you can’t rely on your new state values you apply in setState to be applied immediately. Therefore, if you change the component’s state with setState, there’s a good chance that your changes won’t be applied immediately but instead will be scheduled to happen sometime in future. You can’t rely on your new state values you apply in useState to be applied immediately. If your setState depends on the current value of the state or props, you need to use the functional (the second) form.

1._
this.setState({
   count: 1
})
2._
this.setState({
   count: this.state.count + 1
})
3._
colsole.log(this.state); // Prints 1
5._
// Before this this.state.count is 0
this.setState({
   count: 1
});
this.setState({
   count: this.state.count + 1
});
console.log(this.state.count);
6._
this.setState({
   count: 1,
   tempo: 120
});