badgateway/react-ketting

useCollection is causing re-rendering the component multiple times while fetching data from API

sazyadav opened this issue · 8 comments

useCollection does more re-renders than needed. The sample shared by @sazyadav, does at least 5 renders from (presumably) a cold cache.

We should try to reduce this to 2.

Below is the basic code snippet-

import React, { useState } from "react";
import { useCollection, useResource } from "react-ketting";

const ReactKettingTest = () => {
const [counter, setCounter] = useState(0);
const { loading, error, items } = useCollection('myapiurl');

if (loading) {
console.log("loading..." + loading);
} else {
console.log("loading..." + loading);
}
return (


{loading ? (

Loading......


) : (

{items.length} items are fetched.


)}

);
};

export default ReactKettingTest;


console logs:

loading...true
loading...true
loading...false
loading...false
loading...false

......................
Why i'm getting this multiple times..please help

evert commented

Hi! Can you also add this to your log:

if (error) console.log(error);

I have added but not getting any error..

evert commented

Did you figure it out?

Did you figure it out?

no i am still in dilemma why useCollection is causing re-rendering the component.
Even after loading is false , component is re-executing, could you please check and help how can i prevent re-execution

evert commented

Maybe I misunderstood initially. Is the re-rendering continuous, or is it exactly these 5 times:

loading...true
loading...true
loading...false
loading...false
loading...false

it is exactly 5 times...

evert commented

Ok, that's a bug but probably also expected still!

It's pretty hard to eliminate re-renders, but a few have been removed already. I think this is worth trying, so I'll update the title and description and re-open.