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

91
Views
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 answers
Answer question

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 Report
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!