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

284
Views
Nested conditional

I'm trying to assign a value to a variable depending on the viewport size using Hooks in Gatsby I'm using nested conditionals and it works when I test the webpage for the first time but if I resize manually the window browser it displays the following error:

Rendered fewer hooks than expected. This may be caused by an accidental early return statement

As the react Docs says: Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. So I tried using a ternary operation:

let filter = (useMediaQuery({ query: '(max-width: 695px)' })) ? 2 : (useMediaQuery({ query: '(min-width: 900px)' })) ? 4 : 3

I also tried with:

if (useMediaQuery({ query: '(max-width: 695px)' })) 
 { filter = 2 } else if (useMediaQuery({ query: '(max-width: 900px)' })) 
 { filter = 4 } else { filter = 3 }

Could you help me, please?

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

0

According to the rules of hooks, all hooks should be called at the top level of a component.

export function YourComponent() {
  const isSmallFormFactor = useMediaQuery({ query: '(max-width: 695px)' });
  const isMediumFormFactor = useMediaQuery({ query: '(max-width: 900px)' });

  const filter = isSmallFormFactor
    ? 2
    : isMediumFormFactor
    ? 4
    : 3;

  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!