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

213
Views
React State update: updating the state in timer do not update the values correctly

I am trying to render each element in the roles array. This code works in the timer (setInterval) is as follows:

  1. Assigns the duplicate value of the state in let prevRole variable and its corresponding index in the let prevRoleIndex variable.

  2. Renders the string of random characters 10 times iteratively with 50ms delay.

  3. Now the next element in the roles array is assigned to let newRole variable, by adding +1 to previousRoleIndex and then updating the state with newRole variable.

import {useState, useEffect} from 'react'

const roles = ['Web Developer & UX Designer', 'Software Developer / Engineer', 'Blockchain Developer', 'Data Anaylist/ Scientist']

export default function App() {
 
    const [role, setRole] = useState(roles[0])
    const sleep = (value) =>{
        return new Promise(r => setTimeout(r, value));
    }
    const getRandomString = () =>{
        return (Math.random()).toString(36).substring(2);
    }
    useEffect(() => {
        const timer = setInterval(async() => {
            console.log("Timer has started")

            let prevRole = role;
            let prevRoleIndex = roles.findIndex((ele)=>ele===prevRole)
            
            console.log("Previous Role State: "+ prevRole)
            
            for(let i=0; i<10; i++){
                setRole(getRandomString())
                await sleep(50)
            }

            prevRoleIndex = prevRoleIndex+1 >= roles.length? -1: prevRoleIndex
            let newRole = roles[prevRoleIndex+1]
            
            console.log("New Role State: "+ newRole)
            
            setRole(newRole)
          }, 3000);
          return () => clearInterval(timer);
        }, []);
        return(
          <div>
            <h1>{role}</h1>
          </div>
    )
}

The code works fine during first timer iteration and after second iteration the state does not update.

about 4 years ago · Juan Pablo Isaza
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!