Handling API calls using useEffect vs using useCallback
Asked Answered
I

1

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?

Insidious answered 10/8, 2020 at 1:36 Comment(3)
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.Wayfaring
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?Insidious
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 ?Cnossus
C
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])

Classicize answered 10/8, 2020 at 5:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.