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

167
Views
How to validate a parameter before passing it to a React hook?

Here is an example of my code. I want to get a specific element using the id from the URL (NextJS). I want to validate the id first that useElement does not run without a meaning.

const {id} = router.query

// Make sure id is not undefined
const element = useElement(id)

Approach 1

The following code snippet would make sense, but it does not work because React always needs the same number of hooks.

Error: React has detected a change in the order of Hooks called by Foo. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks

const {id} = router.query

if (!id) {
    return null
}

const element = useElement(id)

Approach 2

I also thought of validating directly inside my custom hook. However, React does not allow that.

Uncaught Error: Should have a queue. This is likely a bug in React. Please file an issue.

export function useElement(id) {
  const [element, setElement] = useState()

  if(!id) {
      return undefined
  }

  useEffect(() => {
    ...
  })

  return element
}

What is the best approach to solving this issue?

about 4 years ago · Juan Pablo Isaza
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!