T
TanStack2y ago
quickest-silver

Why is this causing an infinite render loop?

const query = useQuery({queryKey: ["starter-products"], queryFn: getAllProducts});
const [indexOfTargetProduct, setIndex] = useState(0);

useEffect(() => {

}, []);

if (query.isLoading) return;
if (query.isSuccess) {
setIndex(() => query.data.findIndex(e => e.name === urlParams.itemName));
}
const query = useQuery({queryKey: ["starter-products"], queryFn: getAllProducts});
const [indexOfTargetProduct, setIndex] = useState(0);

useEffect(() => {

}, []);

if (query.isLoading) return;
if (query.isSuccess) {
setIndex(() => query.data.findIndex(e => e.name === urlParams.itemName));
}
Why is this setIndex causing an infinite render loop? Maybe I'm forgetting React basics
4 Replies
quickest-silver
quickest-silverOP2y 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
rare-sapphire2y 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
useEffect(() => {
setIndex(() => query.data.findIndex(e => e.name === urlParams.itemName));
}, [query.isSuccess])
useEffect(() => {
setIndex(() => query.data.findIndex(e => e.name === urlParams.itemName));
}, [query.isSuccess])
xenial-black
xenial-black2y ago
index is derived state - you don't need to save it in state
xenial-black
xenial-black2y ago

Did you find this page helpful?