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

117
Views
Switch statement on a timer in React

Trying to automatically increment the index of my switch statement so my site will automatically switch different elements out.

Trying to achieve this using:

export default function MainComponent(props) {
  let index = 0;

  switch (index) {
    case 0:
      counter++;
      console.log(index)
      return (
       //ELEMENT 1
      );
    case 1:
      index++;
      console.log(index)
      return (
      //ELEMENT 2
      );
    case 2:
      index++;
      console.log(index)
      return (
        ELEMENT 3
      );
    case 3:
      index++;
      console.log(index)
      return (
        //ELEMENT 4
      );

    default:
      return (
     null
     )

I can see that the index increments in the console so I don't understand why my switch state isn't switching to the next element.

Any help appreciated

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

0

If I understand you correctly you need to use hooks for the state. Otherwise, React won't rerender your component.

import { useCallback, useState } from "react";

export default function App() {
    let [index, setIndex] = useState(0)
    let increment = useCallback(() => {
      setIndex(index => index + 1);
    }, [setIndex])
  
    switch (index) {
      case 0:
        increment()
        console.log(index)
        return 1
      case 1:
        increment()
        console.log(index)
        return 2
      case 2:
        increment()
        console.log(index)
        return 3
      case 3:
        increment()
        console.log(index)
        return 4
      default:
        return 'default'
    }
}

But renders happen quickly. You will need some timeouts to see different cases on the screen

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!