When creating multiple React Components in a loop with an incrementing counter passed as a prop, why does the counter show the final value?

I'm trying to understand how closures work in javascript.

Here, I'm iterating through values of the 'items' array using a foreach. I've a let variable "count" declared outside the scope of the foreach loop. After each iteration, the value of 'item' is added to 'count'. Inside the loop, I'm declaring a new React Component that renders the value of "count".



export default function App() {
  const comps: ComponentType<any>[] = [];

  let count = 0;
  const items = [5, 1, 3];

  items.forEach((item) => {
    const countCopy = count;
    comps.push((props) => (
      <div>
        {count} : {countCopy}
      </div>
    ));
    count += item;
  });

  return (
    <div className="App">
      {comps.map((Comp) => (
        <Comp />
      ))}
    </div>
  );
}

But when I run the code, the count value that is showed is its last value (9). I need to create a copy "countCopy" of the variable in order to display its current value. Why is that? Is there a cleaner way?

CodeSandbox:

https://codesandbox.io/s/javascript-closure-question-5uwmm



from Recent Questions - Stack Overflow https://ift.tt/2SYTJud
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)