Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

274
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda