Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

272
Views
Why does Javascript map() render my feature where forEach() didn't? Using React with NextJS

I had an issue where my feature wasn't rendering because I don't think React understood the state was changing. After changing the forEach() to map(), the feature rendered as expected.

Feature will take user's subscriptions from an API then render as list. This is the final working version.

...
export default function MyComp() {
  const [userSubIds, setUserSubIds] = useState()

  useEffect(() => {
    getSubs().then(p => setUserSubIds(p))
  }, [])

  return (
    <>
    {
      userSubIds?.map(subId => {
        <ListItem>
          {subId.data}
        </ListItem>
      })
    }
    </>
  )

Previously I had used forEach(). This did not return any error nor any feature on the web page.

...
      userSubIds?.forEach(subId => {
        <ListItem>
          {subId.data}
        </ListItem>
      })
...

From reading the docs, forEach() always returns undefined and map() returns a new array. But what I'm missing in knowledge is why this matters for rendering?

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

This is because, your loop has to return elements. Those elements will go into your tags and thus it will be rendered.

Now, map returns an array of the same size with the modified elements. forEach does not return anything. It is just traversing the array. It does not give react the elements that it needs.

<>
{
  userSubIds?.map(subId => 
    <ListItem>
      {subId.data}
    </ListItem>
  )
}
<>
// This has returned elements like this
<ListItem> some data </ListItem>
<ListItem> some data </ListItem>
<ListItem> some data </ListItem>
...

However, forEach has not returned any data.

userSubIds?.forEach(subId =>
  <ListItem>
    {subId.data}
  </ListItem>
})
// This has returned nothing.
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!