Home > Enterprise >  dependency array in react use effect
dependency array in react use effect

Time:11-24

I'm fetching some data's from GetClient service and sets in state.

const [getSingleClient, setGetSingleClient] = useState({});
useEffect(() => {
        const GetClient = async () => setGetSingleClient(await GetSingle(`${id}`));
        GetClient();
    }, [getSingleClient, id]);

I dependenced it to [getSingleClient, id] but rolls down to inifinite loop and is sending request frequently. I get id from useParams.

can anyone help me?

CodePudding user response:

Now a little explanation on how the dependency array works. The useEffect hook is a function that is triggered always at the first render and then it's triggered whenever an object in its dependency array changes. For this reason, you have to insert in the dependency array only the objects that you want to trigger your hook when they change.

In your case, it seems to me that your hook should be triggered only when your id changes. For this reason, to solve the loop just use:

const [getSingleClient, setGetSingleClient] = useState({});
useEffect(() => {
        const GetClient = async () => setGetSingleClient(await GetSingle(`${id}`));
        GetClient();
}, [id]);

Now let's spend two words on why you got an infinite loop: in your use effect loop, you placed as a dependency your state (getSingleClient). Inside your hook, on the other hand, you set that state to the result of your (I assume) API call, which returns an object. By setting the state you changed your getSingleClient, which is an object in your dependency array. This causes your hook to trigger once again, setting again your state, and ending up in an infinite loop.

CodePudding user response:

Calling setGetSingleClient with getSingleClientas a dependency will trigger useEffect call everytime data is set. So, remove getSingleClient from dependency array

const [getSingleClient, setGetSingleClient] = useState({});
useEffect(() => {
        const GetClient = async () => setGetSingleClient(await GetSingle(`${id}`));
        GetClient();
    }, [id]);
  • Related