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

168
Visualizações
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
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