still learning react a bit and am trying to understand the rendering process… I felt like I had a decent grasp until this current project.
import { useEffect, useState } from "react";
import BazaarPage from "./Components/BazaarPage";
import "./styles.css";
export default function App() {
const [data, setData] = useState();
useEffect(() => {
async function getData() {
fetch("https://api.slothpixel.me/api/skyblock/bazaar")
.then((data) => data.json())
.then((obj) => {
setData(obj);
});
}
getData();
}, []);
return <div className="App">{data && <BazaarPage data={data} />}</div>;
}
export default function BazaarPage({ data }) {
console.log(data);
return <div className="bazzar-page"></div>;
}
This, I would expect, would console.log 1 time… But it renders 4 times…
My thought process being that my "BazaarPage" component wouldn’t render until there is something in the "data" state based on the data && <BazaarPage data={data} /> conditional. I also understand it that the "App" component should render twice, once on initial run of the page and a second time when the state gets updated in my setData in the the useEffect.
Why is this logging the data 4 times and where is my understanding incorrect?
>Solution :
StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).
If you have StrictMode enabled in your app but don’t remember enabling it, it might be because you used create-react-app or similar to create your app initially, which automatically enables StrictMode by default.
For example, you might find that your {app} is wrapped by <React.StrictMode> in your index.js:
ReactDOM.render(
<React.StrictMode>
{app}
</React.StrictMode>,
document.getElementById('root')
);
If so, you can disable StrictMode by removing the <React.StrictMode> tag:
ReactDOM.render(
{app}
document.getElementById('root')
);