How to Use a For Loop in React Functional Components

If you are coming from a traditional programming background, your first instinct is likely to reach for a for loop when you need to repeat a task.

In React, things work a little differently because we are often dealing with JSX, which requires us to return values that can be rendered to the screen.

Over the last 8 years of working with React, I have seen many developers struggle with where exactly to place a for loop inside a functional component.

In this tutorial, I will show you exactly how to use for loops in React and the best practices I follow to keep my code clean.

Why You Can’t Use a For Loop Directly in JSX

One of the most common mistakes I see is trying to put a for loop directly inside the return statement of a component.

In React, the return statement expects an expression that evaluates to a value (like a string or an object), but a for loop is a statement.

Because a for loop doesn’t “return” a value on its own, React will throw a syntax error if you try to wrap it in curly braces inside your JSX.

To get around this, we have to execute the loop outside the return statement or use an immediately invoked function.

Method 1: Use a For Loop Outside the Return Statement

This is my favorite way to handle complex logic because it keeps the component’s JSX very readable.

I usually create an empty array, run my for loop to push JSX elements into that array, and then render the array in the return block.

Let’s look at an example where we list popular National Parks in the USA.

import React from 'react';

const NationalParksList = () => {
  const parks = [
    { id: 1, name: 'Yellowstone', state: 'Wyoming' },
    { id: 2, name: 'Yosemite', state: 'California' },
    { id: 3, name: 'Grand Canyon', state: 'Arizona' },
    { id: 4, name: 'Zion', state: 'Utah' },
  ];

  // I create an empty array to store the JSX elements
  const parkItems = [];

  // I use a standard for loop to iterate through the data
  for (let i = 0; i < parks.length; i++) {
    parkItems.push(
      <li key={parks[i].id} style={{ marginBottom: '10px' }}>
        <strong>{parks[i].name}</strong> — Located in {parks[i].state}
      </li>
    );
  }

  return (
    <div style={{ padding: '20px', fontFamily: 'Arial' }}>
      <h1>Top National Parks in the USA</h1>
      <ul>
        {/* I simply call the array here */}
        {parkItems}
      </ul>
    </div>
  );
};

export default NationalParksList;

I executed the above example code and added the screenshot below.

For Loop in React Functional Components

In the code above, I defined the parkItems array before the return. This approach is great when you need to perform heavy calculations inside the loop.

Method 2: Use an Immediately Invoked Function Expression (IIFE)

Sometimes, I don’t want to define variables outside the return block because I want to keep the logic tied directly to the UI structure.

In these cases, I use an IIFE (Immediately Invoked Function Expression) inside the JSX.

This allows me to run a for loop right where the content will appear, though it can look a bit cluttered if the loop is long.

Here is an example listing common Tech Hubs in the United States.

import React from 'react';

const USATechHubs = () => {
  const hubs = ['Silicon Valley, CA', 'Austin, TX', 'Seattle, WA', 'New York City, NY', 'Boston, MA'];

  return (
    <div style={{ padding: '20px' }}>
      <h2>Major Tech Hubs in the USA</h2>
      <ol>
        {(function() {
          let rows = [];
          for (let i = 0; i < hubs.length; i++) {
            rows.push(<li key={i}>{hubs[i]}</li>);
          }
          return rows;
        })()}
      </ol>
    </div>
  );
};

export default USATechHubs;

I executed the above example code and added the screenshot below.

Use a For Loop in React Functional Components

I find this method useful for small, quick loops, but I generally avoid it for larger components as it can make the component harder to debug.

Method 3: Generate a Range with a For Loop

A very common scenario I encounter is needing to render a specific number of items, like a star rating for a product review or a list of years.

Since we don’t always have an array to loop through, I use a for loop to generate a range of numbers.

Let’s create a simple review component for a restaurant in Chicago.

import React from 'react';

const RestaurantReview = () => {
  const rating = 5;
  const stars = [];

  // I loop based on the rating number
  for (let i = 0; i < rating; i++) {
    stars.push(<span key={i} style={{ color: 'gold', fontSize: '24px' }}>★</span>);
  }

  return (
    <div style={{ border: '1px solid #ccc', padding: '15px', borderRadius: '8px', width: '300px' }}>
      <h3>Lou Malnati's Pizzeria</h3>
      <p>Best deep-dish pizza in Chicago!</p>
      <div>{stars}</div>
    </div>
  );
};

export default RestaurantReview;

I executed the above example code and added the screenshot below.

How to Use a For Loop in React Functional Components

This is a clean way to handle repetitive UI elements that aren’t necessarily tied to a data object.

The Standard Alternative: Using the Map Method

While for loops are perfectly valid, I must mention the map() method because it is the “React way” of doing things.

The map() method is an expression, which means you can use it directly inside your JSX without needing an IIFE or external arrays.

Most experienced developers prefer map() because it is more declarative and concise.

Here is how I would write a list of famous US Landmarks using the map method.

import React from 'react';

const Landmarks = () => {
  const landmarks = [
    'Statue of Liberty',
    'Golden Gate Bridge',
    'Mount Rushmore',
    'Space Needle'
  ];

  return (
    <div style={{ padding: '20px' }}>
      <h2>Must-Visit US Landmarks</h2>
      <ul>
        {landmarks.map((landmark, index) => (
          <li key={index}>{landmark}</li>
        ))}
      </ul>
    </div>
  );
};

export default Landmarks;

The primary reason I use map() over a for loop is that it creates a new array automatically and returns it, making the code much shorter.

Important Note on Keys

Regardless of which method you choose, you must always provide a unique key prop to the top-level element inside your loop.

React uses these keys to keep track of which items have changed, been added, or been removed.

If you don’t provide a key, you might see strange rendering bugs or performance issues when the list updates.

I always try to use a unique ID from my data (like a database ID) rather than the array index whenever possible.

Performance Considerations

In terms of raw speed, a traditional for loop is technically faster than the map() method in JavaScript.

However, in the context of a React application, the performance difference is usually so small that you won’t notice it.

I recommend choosing the method that makes your code the easiest to read and maintain for your team.

If you are dealing with tens of thousands of rows, you might want to look into “windowing” libraries like react-window instead of a standard loop.

In this tutorial, I showed you how to use a for loop in React functional components using several different methods.

I also explained why you cannot use a for loop directly inside JSX and how to use the map method as a cleaner alternative.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.