I have Function Component that utilizes hooks. In the useEffect hook, I simply want to fetch data from my back end and store the results in state. However, despite adding the data variable as a dependency, useEffect still fires on an infinite loop - even though the data hasn't changed. How can I stop useEffect from firing continuously?
I've tried the empty array hack, which DOES stop useEffect from continuously firing, but it's not the desired behavior. If the user saves new data, for example, useEffect should fire again to get updated data - I'm not looking to emulate componentDidMount.
const Invoices = () => {
const [invoiceData, setInvoiceData] = useState([]);
useEffect(() => {
const updateInvoiceData = async () => {
const results = await api.invoice.findData();
setInvoiceData(results);
};
updateInvoiceData();
}, [invoiceData]);
return (
<Table entries={invoiceData} />
);
};
I expected useEffect to fire after the initial render, and again ONLY when invoiceData changes.
invoiceData
. The second argument inuseEffect
will handle that better and will only execute the code when value ininvoiceData
is changed. But if the value is getting changed every time you are making a call then this won't work. – Milind AgrawalupdateInvoiceData
logic to separate method and useuseEffect
only for the first time and then whenever new data is saved, call the method again(Do not useuseEffect
) – Milind Agrawal