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

135
Views
How to avoid React Hooks inside loops and conditions?

I have the following problem: I am using an Use Effect Hook to update my taskList when I open my WebApp. So I have to lists a list with task which has the attribute recurring tasks (recuringTaskManager.lastWeeklyReset) and a list which can have attributes with recurring and without (taskList). So my goal is to update taskList with the other one when a special condition occur (if differenceInDays....). so I want to delete some tasks in Taskslist therefore the filter function and add them again so that a special attribute can get refreshed. I found out that using hooks in conditions and loops is always bad but I don't know how I could code it without loops and conditions.

Maybe you know

useEffect(() => {
    if (!isInitialized) return
    if (differenceInDays(new Date("July 28, 2022 00:00:00"), state.recuringTaskManager.lastWeeklyReset) >= 7) {
      for (let task of state.recuringTaskManager.recuringTaskListWeekly) {
        const {id} = task
        setState({...state, taskList: state.taskList.filter((task: Task) => task.id !== id)})
state.recuringTaskManager.recuringTaskListWeekly)
      }

      setState({...state, taskList: [...state.recuringTaskManager.recuringTaskListWeekly, ...state.taskList]})
    }
  }, [isInitialized])
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

What you can do to avoid that is to set a variable and increment it in the loop and then set the state outside the loop or I think for your case you can just do this in one line

setState({...state, taskList: state.taskList.filter(({id}) => !state.recuringTaskManager.recuringTaskListWeekly.some(({id: id2}) => id === id2))})

The some method return true if one of the item of the array met the condition, if not it returns false

about 4 years ago · Santiago Trujillo 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!