Search code examples
reactjsreact-hooksfetchuse-effectuse-state

React - API call within useEffect or not


I'm curious about the difference is using a useEffect hook to handle an API call vs just handling the API outside of an effect.

For example, with useEffect you might do something like

const MyComponent = () => {
  const [myState, setMyState] = useState([])
  const [trigger, setTrigger] = useState(false)

  useEffect(() => {
    const getData = async () => {
      const callMyApi = await fetch('http://someApi.com')
      setMyState(await callMyApi.json()
    }

    if(trigger) {
      getData()
    }
  }, [trigger])

  return (
    <button onClick={setTrigger(true)}>Click me</button>
  )
}

Vs, removing the useEffect

const MyComponent = () => {
  const [myState, setMyState] = useState([])

  const getData = async () => {
    const callMyApi = await fetch('http://someApi.com')
    setMyState(await callMyApi.json()
  }

  return (
    <button onClick={getData()}>Click me</button>
  )
}

That code isn't exact. But the point is, with hooks, are there pitfalls to not using useEffect to handle the fetching of data and updating state?


Solution

  • Ideally,

    if you want to make an API call on click of a button there is no need to use any hook like useEffect and useState, the way you did. your second approach is perfect and there is nothing wrong with that.

    But if there is some specific usecase where it is required then there is nothing wrong in using hooks also you will just be making some extra rerenders but if that serves your use case then I guess that is fine too.

    note:

    <button onClick={setTrigger(true)}>Click me</button>
    

    this is wrong, this setTrigger function will be call on mount of the component and I guess you might not want that.

    you can instead do

    <button onClick={()=>setTrigger(true)}>Click me</button>
    

    OR

    const MyComponent = () => {
      const [myState, setMyState] = useState([])
    
      const getData = async () => {
        const callMyApi = await fetch('http://someApi.com')
        setMyState(await callMyApi.json()
      }
    
      return (
        <button onClick={getData}>Click me</button>
      )
    }