I have been working with react-hooks for a while now, and was under impression useEffect is called once there is some changes been made. But in my case when calling api in useEffect, it renders data continuously.
Here is my useEffect code:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
export default function BookFunction() {
const [bookData, setBookData] = useState([])
useEffect(() => {
function fetchInfo() {
axios.post(`/api/book/bookDetails`).then((data) => {
setBookData(data.data)
}).catch(error => {
console.log(error);
})
}
fetchInfo()
}, [])
console.log('this is bookdata',bookData) => bookdata is printed in the browser again and again
}
when I do console.log(bookData), it renders over and over again in browser.
How can I prevent this, such that it renders only once or twice?
I tried doing without using useEffect as,
function fetchInfo() {
axios.post(`/api/book/bookDetails`).then((data) => {
setBookData(data.data)
}).catch(error => {
console.log(error);
})
}
fetchInfo()
But it crashed the system.
Is there anyother way such that I can achieve my goal? If anyone needs any further information please let me know.
useEffect
should run only once, on mount. However, it's important to know where exactly have you put theconsole.log
. – Plabon DuttafetchInfo
) inside the useEffect and then call it, but not directly execute the content of thefetchInfo
function? – Sinan Yaman