Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

275
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda