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

237
Visualizações
Why shouldn't we change the array list directly by pop and push and instead use the filter method? JS, React

Here is my component which will be mapped and rendered several times in the app. When you clicks on it, its title will be added to an array list and if it was already added to the list it will be removed from the array list (toggle):

export default function Card({ title, info, id, list, setList }) {
  return (
    <div className="bg">
      <h1 className="color">{id}</h1>
      <h2 className="color">{title}</h2>
      <p className="color">{info}</p>
      <button
        onClick={() => {
          if (list.includes(title)) {
            setList(list.filter((el) => el !== title));
          } else setList([...list, title]);
        }}
      >
        click to add
      </button>
    </div>
  );
}

The way I achieved this was by using the filter and {[...list], title}. I was told not to modify the array directly and I have no idea why. Push and pop methods could have easily handled this logic. What makes them ineffective?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Quoting from the docs:

Props are Read-Only

Whether you declare a component as a function or a class, it must never modify its own props. Consider this sum function:

function sum(a, b) {
  return a + b;
}

Such functions are called “pure” because they do not attempt to change their inputs, and always return the same result for the same inputs.

In contrast, this function is impure because it changes its own input:

function withdraw(account, amount) {
  account.total -= amount;
}

React is pretty flexible but it has a single strict rule:

All React components must act like pure functions with respect to their props.

Of course, application UIs are dynamic and change over time. In the next section, we will introduce a new concept of “state”. State allows React components to change their output over time in response to user actions, network responses, and anything else, without violating this rule.

about 4 years ago · Juan Pablo Isaza 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