Robin Singh
Robin Singh

Reputation: 1796

How to fix React state update on click button twice?

I am working with webpack and react. I create count increment in my application, but when i click on button state not changed, But when i click again than count increment or you can say state updated. Please check my code below and let me know where i am wrong.

You can check in below image i clicked twice but count is 1.

enter image description here

import React, { useState } from "react";

const Count = () => {
  let [count, setCount] = useState(0);

  function click() {
    console.log("clicked");
    setCount(count++);
  }
  return (
    <div>
      <button onClick={click} className="btn btn-primary">
        Click here
      </button>
      <h3>{count}</h3>
    </div>
  );
};

export default Count;

Any solution appreciated!

Upvotes: 4

Views: 3657

Answers (4)

akhtarvahid
akhtarvahid

Reputation: 9769

Use previous state

 function click() {
    console.log("clicked");
    setCount(prevCount => prevCount+1);
    //or
    //setCount(count+1);
  }

Upvotes: 1

chawki challadia
chawki challadia

Reputation: 454

ok you have one of three solutions:

  • pass a function to your set state: like setCount(prevState => prevState +1)
  • do a pre-increment instead like: setCount(++count)
  • add manually with using increment like: setCount(count + 1)

your code does not work because you are using a post-increment operation, which uses the value then increment 1 to it which caused the confusion you are currently facing.

Upvotes: 7

Hossein Ahmadi
Hossein Ahmadi

Reputation: 464

counter++ is post incremental and it uses the count value first and then plus 1 to it. so, first time you click on the button, it sets count with count and then add 1 to it. to use pre incremental ++count or count + 1 instead of count++

Upvotes: 1

Louis Coulet
Louis Coulet

Reputation: 4591

In React, state update is asynchronous.
You should write:

setCount(previousCount => previousCount + 1);

To learn more: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

Upvotes: 3

Related Questions