Search code examples
reactjsreact-hooksuse-effect

React useEffect calls API too many time, How can I limit the API call to only once when my component renders?


I am calling a get API in useEffect hook, to get the data before component mounts, but it's calling the API to many time and I am getting an error "To many API calls".

const [total, setTotal] = useState(0);
const [message, setMessage] = useState('');

useEffect(() => {
    covidApi.getData({url:'/totals'})
    .then((response) => {
        setTotal(response.data[0]);
        setMessage('');
        console.log(response.data);
    })
    .catch((error) => {
        setMessage("No data found");
        console.log(error);
    })
});

Output:

Browser Output

Please let me know is it the best way to get data from API before your component renders using useEffect hook.


Solution

  • Put a [] after the function in useEffect like this:

    useEffect(() => {
        covidApi.getData({url:'/totals'})
        .then((response) => {
            setTotal(response.data[0]);
            setMessage('');
            console.log(response.data);
        })
        .catch((error) => {
            setMessage("No data found");
            console.log(error);
        })
    }, []);
    

    This will call the API only once.