DEV Community

Cover image for How to Loop Through Arrays in React (The Right Way)
adams.nxt
adams.nxt

Posted on • Originally published at Medium

How to Loop Through Arrays in React (The Right Way)

If you’re learning React, at some point you’ll hit this question:

“How do I properly loop through arrays?”

And yeah… you can use a for loop — but that’s not how React is meant to work.

Let’s break it down simply.

🧠 The React Way: map()
In React, the correct way to render lists is using JavaScript’s .map() method.

Why?

Because React is declarative — you describe what the UI should look like based on data.

Example:
const users = ["Adam", "Sophia", "Lucas"];
function App() {
return (


{users.map((user, index) => (

{user}


))}

);
}
👉 This takes each item in the array and turns it into UI.

⚠️ The Key Problem (Most Devs Ignore This)
React needs a way to identify each element in the list.

Become a Medium member
That’s where the key comes in.

❌ Bad:
{users.map((user, index) => (

{user}


))}
✅ Better:
const users = [
{ id: 1, name: "Adam" },
{ id: 2, name: "Sophia" },
];
{users.map((user) => (

{user.name}


))}
👉 Always use a unique and stable value.

🚫 Why NOT use for or forEach
You might think:

“Why not just loop like normal?”

Because:

forEach() does not return anything → React can’t render it
for loops break the declarative pattern
You end up writing more code for worse results
🔁 Real World Example
Let’s say you fetch data from an API:

const [users, setUsers] = useState([]);
useEffect(() => {
fetch("/api/users")
.then(res => res.json())
.then(data => setUsers(data));
}, []);
Rendering it:

return (


{users.map(user => (

{user.name}


{user.email}



))}

);
💥 Common Mistakes
Forgetting the key
Using index when the list can change
Trying to use forEach
Mutating the array before rendering
⚡ Clean Pattern (Pro Tip)
Extract components:

function UserCard({ user }) {
return (


{user.name}


{user.email}



);
}
{users.map(user => (

))}
👉 Cleaner, reusable, scalable.

🚀 Final Thoughts
If you remember one thing:

React doesn’t “loop” — it transforms data into UI.

Mastering .map() is one of the first steps to thinking like a React developer.

👋 Follow for more
I share simple, real-world programming tips and snippets.

Follow me as @adams.nxt

You can find more code examples on my GitHub:
https://github.com/adamsnxt

Top comments (0)