This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
14
Why is my useState hook always 1 number behind?
Post Body
The calculated average should be 0.55555....
I figured that if I would update using a new variable it would return the actual value, but it is always one behind when calculating the average score.
Could somebody explain this to me? I also tried using the UseEffect hook, but i'm not sure what the argument should be and where I should place the useEffect hook.
const App = () => {
// save clicks of each button to its own state
const [good, setGood] = useState(0);
const [neutral, setNeutral] = useState(0);
const [bad, setBad] = useState(0);
const [total, setTotal] = useState(0);
const [average, setAverage] = useState(0);
const handleGoodClick = () => {
const updatedGood = good;
setGood(updatedGood 1);
setTotal(total 1);
calculateAverage();
};
const handleNeutralClick = () => {
const updatedNeutral = neutral;
setNeutral(updatedNeutral 1);
setTotal(total 1);
calculateAverage();
};
const handleBadClick = () => {
const updatedBad = bad;
setBad(updatedBad 1);
setTotal(total 1);
calculateAverage();
};
const calculateAverage = () => {
const score = good - bad;
setAverage(score / total);
};
Author
Account Strength
80%
Account Age
6 years
Verified Email
Yes
Verified Flair
No
Total Karma
55
Link Karma
38
Comment Karma
17
Profile updated: 4 days ago
Posts updated: 5 months ago
Subreddit
Post Details
We try to extract some basic information from the post title. This is not
always successful or accurate, please use your best judgement and compare
these values to the post title and body for confirmation.
- Posted
- 1 year ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/react/comme...