Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda