Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix React state update on click button twice?

Tags:

reactjs

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!

like image 305
Robin Singh Avatar asked Oct 15 '25 22:10

Robin Singh


1 Answers

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.

like image 87
chawki challadia Avatar answered Oct 17 '25 12:10

chawki challadia