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

67
Views
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 answers
Answer question

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 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!