Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

215
Views
React how can I change a state based on a different state, in the same function
import React, {useState, useEffect} from 'react';
  
 
const Test = ( {numar}) => { 
    const [likeStatus, setLikeStatus] = useState(true);
    const [likeNumber, setLikeNumber] = useState(100);
 
    const onLikeHandler = () => { 
        setLikeStatus(prevState => !prevState);
        if(likeStatus){
            setLikeNumber(prevState=> prevState +1)
        } else {
            setLikeNumber(prevState=>prevState-1);
        }
    }
 
    console.log(likeStatus);
    console.log(likeNumber);
 
    return <button className={`like ${likeStatus ? 'liked' : ""}`} onClick={onLikeHandler}>{`Like | ${ likeNumber}`}</button>
}
 
export default Test;

I am trying to make a like button that likes/unlikes based on the click.

How can I make the second change state function wait for my first state function to finish? I tried using an use effect hook, and I am using the likeStatus in the dependecy array, but for some reason "the unlike" function triggers twice upon refresh"

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

State update is async, and state is being accessed from closure which recreates only after rerender - meaning you can not set state and then in next line to expect that you will get that new state immediately, you will get new state but only in next function call(after element rerenders). Solution is to preserve new state in temp variable.

Rewrite to this:

    const onLikeHandler = () => {
    const newLikeStatus = !likeStatus; // Here you are preserving that new state in temp variable
    setLikeStatus(newLikeStatus);

    if(newLikeStatus){
        setLikeNumber(prevState=> prevState +1)
    } else {
        setLikeNumber(prevState=>prevState-1);

    }


}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!