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

321
Views
React : How to call setState twice if the second relies on the first?

How do I achieve this simple logic in react if the second setState hook depends on thee first one to change first? In this example, the first setState value doesn't update fast enough before running the second setState. I have tried putting the second one in a timeout, as well as putting it inside a callback function of the first. Didn't work out. The useEffect might solve this issue but in this particular instance I would need to call useEffect only in the first one and not every time there is a state change. Let me know your thoughts.

function blah(arg) {
    if (condition) {
        setState(arg)
    }
    setState(state + 1)
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

React's State isn't meant to work as a variable. When you call setState, you are simply telling the code what value it is supposed to use in the next rendering of the component. It will never set the value immediatly.

If you need it to behave as a variable, just use variables and call setState a single time at the end.

function blah(arg) {
    let aux = state;
    if (condition) {
        aux = arg;
    }
    setState(aux + 1);
}
about 4 years ago · Juan Pablo Isaza Report

0

you need to use the useEffect hook :

const [state, setState] = useState();

useEffect(() => {
    // get executed  whenever state is changed
}, [state])


function blah(arg) {
    if (condition) {
        setState(arg)
    }
}
about 4 years ago · Juan Pablo Isaza Report

0

First Load up on the function

import React, { useState, useEffect } from 'react';

Then

const [ListValue, setListValue] = useState([]);
  
useEffect(() => {
    console.log(ListValue)
}, [])


function blah(arg) {
    if (condition) {
        setListValue(arg)
    }
}
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!