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

231
Views
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 answers
Answer question

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 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!