0

I am doing get request to backend to fetch data from database, Im doing something like :

   const loadData = async () => {
        const response = await fetch(URL);
        const data = await response.json();
        setOrdersData(data.data);
    };

    useEffect(() => {
        loadData();
        console.log(OrdersData)
    }, []);

when i console.log(OrdersData) it console.log 6 times thus in rendering the data it rendering it 6 times as well, i also tried to set dependency in useEffect like as follow:

 const loadData = async () => {
        const response = await fetch(URL);
        const data = await response.json();

        setOrdersData(data.data);
    };

    useEffect(() => {
        loadData();
        setLoading(false)
        console.log(OrdersData)
    }, [loading]);

But still when i render OrdersData it rendering it 6 times even though the response result is only one object, i couldn't figure it out how to not duplicate the data.

anie
  • 399
  • 5
  • 17
  • Does this answer your question? [UseEffect being called multiple times](https://stackoverflow.com/questions/62631053/useeffect-being-called-multiple-times) – Maifee Ul Asad Jun 30 '21 at 08:33
  • @MaifeeUlAsad no still rendering same data more than once – anie Jun 30 '21 at 08:47

1 Answers1

0

To prevent unnecessary renders try to use the useCallback hook in the loadData as so:

const loadData = useCallback(async () => {
    try {
      const response = await fetch(URL);
        const data = await response.json();

        setOrdersData(data.data);
    } catch (err) {
      //do something
    }
  }, [])

Remember to import as hook, and use the dependecies as you please like useEffect or useMemo. Hoping it works remember also to unmount the the side effects in useEffect with return statement

Wiidialga18
  • 331
  • 1
  • 8