1 min read
Don’t let reverse() backfire in React
Posted byThức Trần

mutates the original array. That’s fine in isolated scripts, but inside a React render it can lead to surprising UI, especially in React 18 Strict Mode (development) where React intentionally invokes render twice to surface side effects.Array.prototype.reverse()
Consider a parent passing an array as props:
// Parent.jsx export default function Parent() { const items = [1, 2, 3]; // imagine this actually comes from state/props return <Products items={items} />; }
And the child mutates that array during render:
// Products.jsx (❌ anti-pattern) export function Products({ items }) { return <ul>{items.reverse().map(i => <li key={i}>{i}</li>)}</ul>; }
In Strict Mode (dev only), React calls your component function twice; the first render is discarded, but your side-effect (mutating ) is not. So:items
Even outside Strict Mode, mutating props/state in render is still an anti-pattern: it breaks render purity, can cause flickers on re-renders, and ruins memoization.
Use a non-mutating approach:
export function Products({ items }) { return <ul>{items.toReversed().map(i => <li key={i}>{i}</li>)}</ul>; }
export function Products({ items }) { return <ul>{items.slice().reverse().map(i => <li key={i}>{i}</li>)}</ul>; // or: [...items].reverse() }
If the list is large and items changes infrequently, you can memoize:
import { useMemo } from "react"; export function Products({ items }) { const reversed = useMemo(() => items.toReversed(), [items]); return <ul>{reversed.map(i => <li key={i}>{i}</li>)}</ul>; }
As simple as that to keep your component pure and predictable.
Hope this helps!
Posted by