-2

What cause printing every array index twice time using map method. Does component is double rendered? Why it working like that?

import React from 'react';
    
const data = [
  { id: 1, name: 'john' },
  { id: 2, name: 'peter' },
  { id: 3, name: 'susan' },
  { id: 4, name: 'anna' },
];
    
const UseStateArray = () => {
  const [people,setPeople] = React.useState(data)

  return <>
  {
    people.map((person)=>{
      console.log(person);
    })
  }
  </>;
};

My output in console is:

{id: 1, name: "john"}
{id: 2, name: "peter"}
{id: 3, name: "susan"}
{id: 4, name: "anna"}
{id: 1, name: "john"}
{id: 2, name: "peter"}
{id: 3, name: "susan"}
{id: 4, name: "anna"}
Telirw
  • 373
  • 3
  • 15
  • 2
    not able to reproduce – brk Aug 01 '21 at 14:40
  • Unless you show your full [mcve], there is no way of telling how many times your full app, or the subtree that includes ``, gets rendered. Just dropping this code into a minimal example with an `` that only returns shows things doing exactly what you'd expect, rendering only once. https://codesandbox.io/s/react-hooks-counter-demo-forked-rbtj6 – Mike 'Pomax' Kamermans Aug 01 '21 at 14:43

1 Answers1

2

If you look at this codesandbox example with your code you can see on the console tab that the console log is happening only once https://codesandbox.io/s/nervous-hill-0k32k?file=/src/App.js

Most likely the parent component on which you are rendering this component is causing a re-render that's why the console.log appear twice.

showing console log sample

I find this stackoverflow answer very useful to track what property change is causing the parent component to re-render Trace why a React component is re-rendering

Besnik Korça
  • 939
  • 3
  • 9