8

This is very likely a dumb question -- I have the understanding that anything that triggers a side-effect should be handled with useEffect. I was wondering if that understanding is correct. Particularly in the context of making an API call -- is it good to make API calls in a useCallback hook?

Eddie Lam
  • 579
  • 1
  • 5
  • 22
  • 1
    When do you want the api call to occur? If it's connected to the component rendering (eg, on mount), use an effect. If it's in response to some user action (eg, a click), use a callback. – Nicholas Tower Aug 10 '20 at 01:43
  • oh cool cool -- i wanted it to happen when a state's value changes after a click. Do you know any good article I can read to get a deeper understanding of component lifecycle btw? – Eddie Lam Aug 10 '20 at 01:48
  • I was wondering the same also. Is your question answered ? Even if the params to the callback has not changed, the data might have been changed in the server. So it makes sense to use useCallback ? I still not find an affirmative answer. Any ideas ? – EBDS Aug 02 '23 at 00:50

1 Answers1

8

If you want to do it based on some kind of prop or state change, use the useEffect hook, e.g.,

useEffect(async ()=> {
    const user = await userApi.get(props.id) // Api call here
    
    setUser(user)
}, [props.id]})

If you want to do so on a button click (or any event),

const handleClick = () => {
    const user = await userApi.get(props.id)
        
    setUser(user)
}

useCallback isn't really relied on for api calls or side-effects. useCallback is basically storing a "version" of a function, based on dependencies. When a dependency changes, you get a new function, because what it returns will be different, e.g.,

// props.id = 1
const doSomethingCallback = useCallback(() => { 
    /* do something with props.id */
}, [props.id])

While props.id === 1, doSomethingCallback will always reference the function as it was declared on the first render. If props.id changes to 2, useCallback will reference a new function. So, if doSomethingCallback was a dependency of a useEffect, when props.id changed to 2, useCallback would point to a new function, which would then get noticed by the useEffect and run whatever was in it, e.g.,

useEffect(() => { /* side-effect stuff */}, [doSomethingCallback])

BDurand
  • 108
  • 1
  • 10
Yatrix
  • 13,361
  • 16
  • 48
  • 78