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

100
Visualizações
Calling useState inside useEffect on DOM load

I am building an app to track habits, and when a user is directed to a dashboard, I want them to immediately see their habits as pulled from a database. I have tried calling useState from within useEffect, but I know that there are problems inherent in doing so. I have tried providing a second argument to useEffect to get around this, but am still receiving an invalid hook call error.

const Dashboard = () => {
  const [refetch, setRefetch] = useState(true);
  const [habits, setHabits] = useState([]);
  useEffect(() => {
    if(refetch){
      fetch('/habits/getHabits', {
        method: "POST",
        headers: {"Content-Type": "application/json; charset=UTF-8"},
        body: JSON.stringify({username: 'Phil'})
      })
      .then((data) => data.json())
      .then((data) => {
        const habitCards = [];
      for(let habit of data.habits){
        habitCards.push(
          <Habit 
          key={habit.habitid}
          habitname={habit.habitname}
          moneyspent={habit.moneyspent}
          lasttime={habit.lasttime} 
          />
        )
      }
      setHabits(habitCards);
    })
    .finally(() => setRefetch(false))
    }
  }, [refetch])
  return (
    <div className='dash'>
      <h1>Your habits:</h1>
      {habits}
    </div>
  )
}

How can I modify this so that useEffect is only called when the page loads, and state is updated from within it?

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

0

If you want your effect to run only once when the page loads, then pass an empty dependency array [] as the second parameter.

When you pass an empty dependency array, you're telling React that this effect does not rely on any values from props or state, and that it never needs to re-run.

  useEffect(() =>
  {
      fetch('/habits/getHabits', {
        method: "POST",
        headers: {"Content-Type": "application/json; charset=UTF-8"},
        body: JSON.stringify({username: 'Phil'})
      })
      .then((data) => data.json())
      .then((data) => {
        const habitCards = [];
        for(let habit of data.habits){
          habitCards.push(
            <Habit 
              key={habit.habitid}
              habitname={habit.habitname}
              moneyspent={habit.moneyspent}
              lasttime={habit.lasttime} />
        )
      }
      setHabits(habitCards);
    })
  }, [])

In this case you would no longer need your refetch state variable.

You can read more about skipping effects here.

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