Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the best use of useEffect to fetch multiple data?

I'm some confused about some different ways to use the useEffect hook to fetch API data. I want to know if there is a "best way" to do this, performance related, or if it really doesn't matter how to do it.

Consider the following ways:

Mutiple function calls to fetch API data inside a single useEffect:

useEffect(() => {
  const fetchStudents = async () => {
    const students = await studentService.getAll()
    setStudents(students)
  }

  const fetchCourses = async () => {
    const courses = await courseService.getAll()
    setCourses(courses)
  }

  const fetchSchedules = async () => {
    const schedules = await scheduleService.getAll()
    setSchedules(schedules)
  }


  fetchStudents()
  fetchCourses()
  fetchSchedules()
}, [])

A single function call to fetch all the api data inside a single useEffect:

useEffect(() => {
  const fetchAllData = async () => {
    const students = await studentService.getAll()
    const courses = await courseService.getAll()
    const schedules= await scheduleService.getAll()

    setStudents(students)
    setCourses(courses)
    setSchedules(schedules)
  }

  fetchAllData()
}, [])

Maybe, multiple useEffects for each api call:

useEffect(() => {
  const fetchStudents= async () => {
    const students = await studentService.getAll()

    setStudents(students)
  }

  fetchStudents()
}, [])

useEffect(() => {
  const fetchCourses = async () => {
    const courses = await courseService.getAll()

    setCourses(courses)
  }

  fetchCourses()
}, [])

useEffect(() => {
  const fetchSchedules = async () => {
    const schedules= await scheduleService.getAll()

    setSchedules(schedules)
  }

  fetchSchedules()
}, [])

Is there another way to consider? Let it be known.

like image 230
David Ferreira Avatar asked Oct 22 '25 10:10

David Ferreira


1 Answers

In your second example you wait for each promise to resolve before executing the next one, this will hurt performance, the other examples are all running in parallel.

I would go with Promise.all inside a single useEffect because i think its more readable then 3 useEffect or 3 functions, and this will also make sure all of our promises are executing in parallel.

Note that if one of the promises inside Promise.all reject, the function is going to throw and you won't have any access to the resolved promises

useEffect(() => {
  Promise.all([
    studentService.getAll().then(setStudents),
    courseService.getAll().then(setCourses),
    scheduleService.getAll().then(schedules)
  ])
}, [])
like image 84
Asaf Aviv Avatar answered Oct 23 '25 22:10

Asaf Aviv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!