Search code examples
javascriptreactjsasynchronoususe-effect

Is it not correct to do api call without useEffect?


I want to do an api call after a button is clicked in react.But I have read that to do async tasks, we use useEffect. So is it okay to not use useEffect and do an api call without it? I think that without using useEffect an api call would block the render. useEffect runs depending on deps Array. It is used to do async tasks. But I want to do a api call onClick.So its not possible to use useEffect. So,What is the correct way to do an api call if it has to be done on Click?


Solution

  • You can do api call with and w/o the useEffect, both are fine.

    And no, you won't block the api call if you don't use useEffect.

    const App =  () => {
      
      const makeApiCall = async () => {
        // the execution of this function stops
        // at this await call, but rest of the App component
        // is still executes
        const res = await fetch("../");
    
      }
    
      ...
    };