Basically we do API calls in componentDidMount() life cycle method in React class components like below
componentDidMount(){
//He
When you are using functional components with the hooks API, you can use the useEffect() method to produce side effects. Whenever the state is updated because of these side effects, the component will re-render.
import { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
You clicked {count} times
);
}
For example, you could call setCount in a callback function of an async request. When the callback is executed, the state will get updated and React will re-render the component. Also from the docs:
Tip
If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as
componentDidMount,componentDidUpdate, andcomponentWillUnmountcombined.