How to use loop in React.js?
Duomly
Posted on July 30, 2020
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
Posted on July 30, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.