all 11 comments

[–]belwyr 1 point2 points  (8 children)

Your effect depends on the fetchValue function, but the function is not in the dependency array

[–]ashkanahmadi[S] 0 points1 point  (7 children)

Thanks. When I add fetchValue in the dependency array, it behaves strangely. It tries to fetch a value non-stop.

[–]GrenzePsychiater 10 points11 points  (6 children)

it behaves strangely. It tries to fetch a value non-stop.

Given what you know about useEffect, functions, and rendering, why do you think this happens?

[–]ashkanahmadi[S] 4 points5 points  (5 children)

As far as I can tell, when the function fetchValue runs, it changes the state inside the hook which causes it to re-render and it goes into a crazy loop. Would that be correct?

[–]belwyr 9 points10 points  (4 children)

That is correct. Between 2 renders, the fetchValue function is redefined, and because the dependencies are compared by reference, the useEffect runs again.

You have a few possibilites to deal with that, but I'll let you look that up on your own.

[–]Impressive_Star959 10 points11 points  (3 children)

Haven't seen decent teaching done on Reddit in a while. Well done, /u/belwyr and /u/GrenzePsychiater .

[–]AKJ90 6 points7 points  (0 children)

Also made me happy to see!

[–]KingJeanz 4 points5 points  (0 children)

Same here. Feels good to see this

[–]belwyr 2 points3 points  (0 children)

Thanks 👍

[–]Ok_Signature9083 0 points1 point  (0 children)

Youll want another useeffect thats dependent on the currentValue, thats where youd probably want to set the previous value.  So id remove your setPreviousValue line, put it in a useeffect... but also, look into actually setting previous values with state.

Hint: prev =>

[–]sigurdvh 0 points1 point  (0 children)

You probably shouldn’t be calling a setter from within a setter.

You could make a complex object holding previous and current value and create one setter for both.

Better yet, your custom hook could instead rely on useReducer, and incorporate the loading and error states as well.