Pure Functions

A pure function is a function that always produces the same result given the same input.

This includes not depending upon external variables such as static variable that the same component manipulates.

React components depend upon this style of code, because this allows for rendering to be idempotent, so components can be re-rendered at anytime and will still produce the same output.

If you want to change the value within a component and want to re-render it, use something like useEffect or state.

Consequences

This will 2 x guest each time cup is called… which makes 0 sense. So just don’t do this!

let guest = 0;

function Cup() {
  // Bad: changing a preexisting variable!
  guest = guest + 1;
  return <h2>Tea cup for guest #{guest}</h2>;
}

export default function TeaSet() {
  return (
    <>
      <Cup />
      <Cup />
      <Cup />
    </>
  );
}

The correct way is to pass the values you want in as props.

function Cup({ guest }) {
  return <h2>Tea cup for guest #{guest}</h2>;
}

export default function TeaSet() {
  return (
    <>
      <Cup guest={1} />
      <Cup guest={2} />
      <Cup guest={3} />
    </>
  );
}

Local mutation

This is totally fine, since the variable is within the component and the function will remain pure.

function Cup({ guest }) {
  return <h2>Tea cup for guest #{guest}</h2>;
}

export default function TeaGathering() {
  const cups = [];
  for (let i = 1; i <= 12; i++) {
    cups.push(<Cup key={i} guest={i} />);
  }
  return cups;
}