Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

69
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda