Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

95
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda