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

68
Visualizações
React hooks with switch-case render

I have a component renders other ones by switch-case

export default function Fragment(props) {
    switch (props.type) {
        
        case FRAGMENT_TYPES.Start:
            return StartFragment(props);

        case FRAGMENT_TYPES.Rules:
            return RulesFragment(props);

        // some other cases
        
        default:    
            return null;
    } 
}

But I get 'order of Hooks error' if StartFragment uses hooks but RulesFragment doesn't.

How can I avoid this error? Should I raise all hooks up in Fragment or there is another method?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I guess you call the function directly

Fragment(props)

instead of the component

<Fragment {...props}/>

Fragment also calls StartFragment and RulesFragment directly. So StartFragment and RulesFragment are then executed in the calling components context. Thus if StartFragment has a hook but RulesFragment don't, it's just like using hooks in conditionals. E.g.

const App = (props) => {
  const fragment = Fragment(props)
  ....
}

App calls function Fragment calls function StartFragment.

But when you use a component

const App = (props) => {
  const fragment = <Fragment {...props}/>
  ....
}

The App doesn't call the function Fragment directly. It calls a React component that has an own state management and this component calls the function Fragment. You can see it when you look at the transpiled code. It should look something like this:

React.createElement(Fragment, props, null);

That's why <Fragment {...props}> works but Fragment(props) don't.

If this is the case I would recommend to change the Fragment function to:

function Fragment(props) {
  switch (props.type) {
    case "Start":
      return <StartFragment {...props}/>;

    case "Rules":
      return <RulesFragment {...props}/>;

    // some other cases

    default:
      return <></>;
  }
}
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