Loading Thucde.dev
Preparing the next view.
1 min read
Don’t let reverse() backfire in React

Array.prototype.reverse() 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.// Parent.jsx export default function Parent() { const items = [1, 2, 3]; // imagine this actually comes from state/props return <Products items={items} />; }
// Products.jsx (❌ anti-pattern) export function Products({ items }) { return <ul>{items.reverse().map(i => <li key={i}>{i}</li>)}</ul>; }
Strict Mode (dev only), React calls your component function twice; the first render is discarded, but your side-effect (mutating items) is not. So: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.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() }
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>; }