Why is this causing an infinite render loop?
Why is this setIndex causing an infinite render loop? Maybe I'm forgetting React basics
4 Replies
quickest-silverOP•2y ago
I guess when I setIndex it checks for isSuccess on the query again
Obviously, right?
I guess what is the correct flow to do this then? I need to set the index after the data is populated, but not get into an infinite loop like above
rare-sapphire•2y ago
State changes makes react rerender
the mental model of react is
ui = f(state)
, everytime state changes, ui gets rerendered
therefore, you run your component(function) and check for query.isSuccess
then you change state, which triggers react to restart rendering the component and looping infinitly
you should use
xenial-black•2y ago
index is derived state - you don't need to save it in state
xenial-black•2y ago
It's this example: https://react.dev/learn/you-might-not-need-an-effect#updating-state-based-on-props-or-state
You Might Not Need an Effect – React
The library for web and native user interfaces