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,018
  • 1
  • 8
  • 23
Shamim Reza
  • 51
  • 1
  • 10
  • 1
    Your component might be rendered multiple times. – mc-user 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

2 Answers2

4

For React.StrictMode issue, the solution can be your rendered component which renders twice that maybe wrap with React.StrictMode. Comment out or clean up the React.StrictMode, I hope it will fix.

In StrictMode, components are rendered twice for ensuring (on development but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).

If StrictMode is enabled in your code, it might be because you used create-react-app or similar to create your app initially, which automatically enables StrictMode by default.

mrseeker53
  • 63
  • 8
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
  • 400
  • 2
  • 11
  • 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