Home > Mobile >  React Component re-rendering unexpectedly
React Component re-rendering unexpectedly

Time:09-13

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?

CodePudding user response:

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')
  );

CodePudding user response:

In React you should not rely on the amount of (re)renders in general as a rule of thumb. Just imagine it will be rendered sufficiently often and so you should keep your components side effect free. Including calling console.log, which is causing a side effect. As the comments above already correctly suggested, wrapping your React-Application into React.StrinctMode causes additional re-renders to prevent you from relying on the amount of renders.

But there can be other side effects like context wrapping your application and causing the App to be updated and so on.

However, your logic was not the problem as you were theoretically right

  • Related