<think><think>
Okay, the user is having trouble with an infinite loop in their React useEffect. Let me see. They mentioned they're fetching data from an API when the component mounts, but updating the state causes the effect to run again, leading to an endless cycle.
Looking at their code, they have the dependency array set to [data]. That makes sense because every time they setData, data changes, triggering the effect again, which fetches and updates data once more, repeating the process. So the key issue here is the dependency array.
Other users already pointed out that using an empty array would fix it if they only want the effect to run once. They should also handle errors and loading states. But maybe the user is confused about how dependencies work. Let me explain why [data] is bad here. Also, perhaps mention that if they need to re-fetch based on some other variable, that variable should be in the dependencies instead. And remind them about cleanup functions if they ever need to unsubscribe from something, but in this case, since it's a fetch, probably not necessary unless they're using async/await and there's a possibility of the component unmounting before the fetch completes. Oh, but actually, if they're using fetch and then setting state, even if the component unmounts, they might still get a warning about updating state on an unmounted component. So maybe suggest checking if the component is mounted before setting state.
Also, they might not know that the empty array is a common pattern for componentDidMount-like behavior. So confirming that approach and explaining that putting data in dependencies causes the loop because setData triggers a re-render, which then re-runs the effect with the new data.
Additionally, maybe mention that if they have other dependencies, they should include those, but in this case, since they want to fetch once on mount, empty array is correct.
They might also benefit from using async/await instead of .then for clarity, but that's not directly related to the loop issue. Still, suggesting that could help them write cleaner code.
So in my response, I should first confirm the problem is the dependency array, then explain the solution of using an empty array, warn about not including data there, and perhaps add tips on error handling and loading states. Also, maybe a note about avoiding unnecessary re-renders if possible. Keep it friendly and helpful, not too technical but clear. Make sure to address the user's specific code issue and the underlying reason so they understand why the fix works.
</think>
Ecco il problema: hai messo `data` come dipendenza in `useEffect`, ma ogni volta che chiami `setData`, React ri-esegue l’effetto perché `data` è cambiata. Questo crea un loop senza fine tra fetch e aggiornamento dello stato. La soluzione è semplice come ha detto @juanmi.ramírez: usa un array vuoto `[]` come dipendenza. Così l’effetto gira solo all’inizio, come un `componentDidMount` classico.
Se proprio vuoi spingerti oltre e renderizzare meglio l’esperienza utente, aggiungi uno stato `isLoading` per mostrare un loader mentre aspetti i dati e uno `error` per gestire fallimenti. Ecco un esempio completo:
```javascript
const [data, setData] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(res => res.json())
.then(data => setData(data))
.catch(err => setError(err))
.finally(() => setIsLoading(false));
}, []);
```
Però stai attento: se metti per sbaglio `setData` dentro una condizione che dipende da `data` stessa (es. `if (data.length === 0)`), puoi ricascare nel loop. Fidati, ci sono passata anch’io. E se ti serve re-fetchare dati in base a qualcosa (tipo un filtro), allora metti *solo quella cosa* nelle dipendenze, non `data`. Gli errori li scopri col tempo, ma React è una figata se usato con testa. Non mollare!