简体   繁体   中英

Component render two times (reactJS)

I have a React Component, when I compile it it renders two times. Some idea?

import React, { useState } from "react";
export default () => {
  const [loaded, setLoaded] = useState(false);
  return (
    <>
      {console.log("test")}
      {alert("y")}
      <h2>Cargando</h2>
    </>
  );
}

You are probably using React.StrictMode , right?

Read about it here https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

It has special mechanism to detect side-effects so in development mode some components will render 2 times instead of one. But it could also happen in production unintentionally but you really should not care about how many times render happened.

How do you know that it renders two times? Because of console.log? It just means that inner mechanisms of react call rendering two times... You should not care about it. It can be called even 10 times if necessary

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM