-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"}
2
  • 2
    not able to reproduce Commented Aug 1, 2021 at 14:40
  • Unless you show your full minimal reproducible example, there is no way of telling how many times your full app, or the subtree that includes <UseStateArray/>, gets rendered. Just dropping this code into a minimal example with an <App/> that only returns <UseStateArray/> shows things doing exactly what you'd expect, rendering only once. codesandbox.io/s/react-hooks-counter-demo-forked-rbtj6 Commented Aug 1, 2021 at 14:43

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

I removed <React.StrictMode> tag from index.js and now console.log appear only once :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.