-1

Why does React show duplicate console.log? I found that to remove StrictMode from index.js. but there was no such problem before and why did I remove StrictMode instead of fixing the issue. What other issues could there be?

see the screenshort: https://prnt.sc/HLAmthr9efoB

import React, { useEffect, useState } from "react";
import Country from "../Country/Country.js";

const gridStyle = {
  display: "grid",
  gridTemplateColumns: "repeat(4, 1fr)",
  gridGap: "20px",
};

const Countries = () => {
  const [countries, setCountries] = useState([]);
  useEffect(() => {
    fetch("https://restcountries.com/v3.1/all")
      .then((res) => res.json())
      .then((data) => setCountries(data));
  }, []);
  console.log(countries);
  return (
    <div className="all-countries">
      <p>{countries.length}</p>
      <div style={gridStyle} className="country-container">
        {countries.map((country) => (
          <Country key={Math.random() * 500000} country={country}></Country>
        ))}
      </div>
    </div>
  );
};

export default Countries;
Amit
  • 1
  • 5
  • 20
  • 1
    Your component might be rendered multiple times. – mchowdam May 13 '22 at 06:40
  • 2
    Can you please provide some code ? Please check https://stackoverflow.com/help/minimal-reproducible-example – RenaudC5 May 13 '22 at 06:40
  • Please provide enough code so others can better understand or reproduce the problem. – Community May 13 '22 at 08:49
  • edited the post with codes – Shamim Reza May 13 '22 at 10:10
  • thats common, react will call your component on every render (in development it happens twice for ensuring) thus console.log() will be executed multiple times. – bogdanoff May 13 '22 at 10:14
  • Refer to this [answer](https://stackoverflow.com/questions/61254372/my-react-component-is-rendering-twice-because-of-strict-mode) to understand why components are rendered twice in StrictMode. – Amit May 13 '22 at 10:24

1 Answers1

0

Most probably you write console.log() outside of function that trigger the log,
so will be fired every time the component is re-rendered.

todevv
  • 73
  • 7
  • no, I use console.log inside the component function. even if used outside the component it's showing perfectly. – Shamim Reza May 13 '22 at 08:47