0

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?

1 Answers1

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.

jsejcksn
  • 27,667
  • 4
  • 38
  • 62