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

594
Visualizações
Difference between useState and useEffect

I use useState instead of useEffect and it works fine for displaying data (why?)

React.useState(() =>getMovies(), [])

Note : I added console.log and I get same results

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When a function is passed to useState, this is signaling to React to use lazy initialization - the function will be invoked to calculate the initial value only when the component mounts.

If the value to be put into state can be calculated/retrieved synchronously, this is probably the best design pattern to use - it's short and doesn't require you to later differentiate between whether the state value is undefined or populated.

const [stateValue, setStateValue] = useState(calculateExpensiveInitialStateValue);

The time to use useEffect is when the value to be populated can't be computed synchronously, in which case the best approach is to have both useState (for the state) and useEffect (to indicate that you want to run a function to retrieve the state value just once).

While you theoretically can have a line just like

React.useState(() =>getMovies(), [])

it's pretty confusing, because

  • The resulting state value returned isn't used
  • useState doesn't accept a second argument dependency array

useEffect is more suited for the task because it doesn't have a return value (unlike useState), and is more flexible, because it does accept a dependency array. useEffect much more clearly indicates to readers of the code "This callback should run only when the dependency array changes."

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