Home > Software design >  How to handle the dependent array in useEffect
How to handle the dependent array in useEffect

Time:03-08

I am new to react and just learned how to use useEffect and useState/useReducer. Now I am facing a problem. Assume I have a useEffect like below and states A,B,C,D:

React.useEffect(() => {
   D = fetchReq(A, B, C);
}, [A, B, C])

React.useEffect(() => {
   B = fetchReq(A)
}, [A])

React.useEffect(() => {
   C = fetchReq(B)
}, [B])

The problem is B also depends on A, so everytime A gets update, B needs to update by an async req accordingly i.e B = fetchReq(A). And C depends on B, C = fetchReq(B). So once if A change, it may trigger incorrect behavior like fetchReq(A,B_old,C_old) or fetchReq(A,B,C_old), which is unwanted.

How should I fix this problem?

CodePudding user response:

Is ABCD an object? If so, look for a more specific property value on that object to use inside of useEffect's trigger condition[]. By doing so, if the value does not change, even if useEffect runs through an interdependent structure, there will be no circularity.

I am sure that the value of the variable required for fetch, does not keep changing every time when it is fetched again.

If that is the case, please write a more specific code example.

CodePudding user response:

I would remove the dependency on A and B in your first effect. C will only update if A is updated (and subsequently B). So, you will not need to listen for changes to A and B, because their change will be a given.

Try that:

React.useEffect(() => {
   D = fetchReq(A, B, C);
}, [C])

React.useEffect(() => {
   B = fetchReq(A)
}, [A])

React.useEffect(() => {
   C = fetchReq(B)
}, [B])
  • Related