React: too many re-renders when using useState in a loop

posée 2 months ago275 vuesen

2

I call setState inside a .map() and React throws "Too many re-renders". What's the correct pattern to compute derived state from an array?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 2 months ago

2 réponses

2
✓
✓ Réponse acceptée

An ORM with parameterized queries prevents injection for values. You still must: validate/whitelist any dynamic identifiers (table/column names), enforce input schemas (e.g. Zod), and apply least-privilege DB roles. Never string-concatenate SQL.

Connectez-vous pour dire si ça a marché.

answered 2 months ago
1

Don't call setState in map. Compute the derived value directly:

const total = items.reduce((s, i) => s + i.price, 0);

If you truly need state, set it once in an effect with the computed result, not per iteration.

Connectez-vous pour dire si ça a marché.

answered 2 months ago

Sign in and verify your email to post an answer.