This article was originally published at https://www.blog.duomly.com/6-most-popular-front-end-interview-questions-and-answers-for-beginners-part-2/#how-to-use-loop-in-react-js
Like the if/else statements, when we would like to do loops in the JavaScript or TypeScript logic, we do not need to bother about any special rules.
It’s just a JS loop, as always, and we can use all types of loops (of course, not all of them are good for all cases, but it’s possible).
Anyway, we have a special reason why we should focus on the iteration methods when we develop apps for React.js.
We use iteration methods to render elements. For example, we can use iteration to render the whole list of products from the product array.
To do that, we can use few methods, one of the most popular is the map method, but we will cover the map in the separate section, and now we should focus on the other methods like loops or forEach method.
It is very popular to use loops like for-loop (in most cases the fastest one), for-in, or for-of to iterate through elements.
That method is useful when we use separate functions to render part of components, and it’s the best method for performance.
The second method that I’ve included in the example is the method with array.forEach().
This method, compared to the for-loops and map method, is the slowest one and doesn’t return the values like a map, so you need to have a special case to use it.
Let’s take a look at the code example with two for-loop and forEach methods:
// First one with For of loop
function renderComponent() {
const products = ['orange', 'apple', 'watermelon'];
const list = []
for (const [i, product] of products.entries()) {
list.push(<li>{product}</li>)
}
return (
<div>
{list}
</div>
)
}
function Parent(props) {
return renderProducts();
}
// Second with forEach method
function renderComponent() {
const products = ['orange', 'apple', 'watermelon'];
const list = []
products.forEach((product) => {
list.push(<li>{product}</li>)
})
return (
<div>
{list}
</div>
)
}
function Parent(props) {
return renderProducts();
}
Thank you for reading,
Radek from Duomly
Latest comments (4)
Nice article! I see you mention
map
, but it's worth emphasizing that it is much more common to usemap
for this kind of thing as it doesn't require declaring your list early, mutating the list, or using side-effects.Also, don't forget to pass the
key
prop!How about using a useMemo() to maintain that arrays reference and only call it when we want to change
Hey Ben, yes, map is a good method to do that, and I've created separated episode about map, that you can watch tomorrow, here: youtube.com/watch?v=Fbc4BvYc4ec
In this one, I wanted to show other popular methods :)
Maybe product is non unique, index still usefull
... but better if prodcut contains key and info