Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this component render twice in react?

Tags:

reactjs

I have a component, I set a count and let state update when button clicked. But when I check render times, it renders twice each time I click the button.

https://codesandbox.io/s/brave-forest-yre6y?file=/src/App.js

export default function App() {
  const cute = Array(10).fill({});
  const [count, setCount] = useState(2);
  console.log(count);
  return (
    <div className="App">
      <button
        onClick={() => {
          if (count < 10) setCount(count + 1);
        }}
      >
        add
      </button>
      {cute.map((data, index) => {
        if (index < count) {
          return (
            <div>
              <p>{index}. Luna is cute</p>
            </div>
          );
        }
      })}
    </div>
  );
}

I wonder:

  1. Why does it work like this?
  2. How could I prevent this?
like image 472
Doraemon Avatar asked Mar 02 '23 08:03

Doraemon


2 Answers

Your app is using StrictMode. See your index.js file - your app is wrapped between a <React.StrictMode> element.

Using StrictMode will cause your app to render twice, but only in development mode. Creating an app with create-react-app will enable strict mode by default.

Here are the official docs for strict mode.

The solution is just to remove <React.StrictMode>, but that will also disable some of its advantages, so if it doesn't bother you, I'd just leave it as is, knowing it won't render like that in production.

See this related question for more details: My React Component is rendering twice because of Strict Mode

like image 74
Adi Ulici Avatar answered Mar 21 '23 02:03

Adi Ulici


Obviously that re-rendering thing is definitely not a bug, or something related with the library's render mechanism. On the contrary it is a debugging mechanism provided by React 🤗

refer this blog https://mariosfakiolas.com/blog/my-react-components-render-twice-and-drive-me-crazy/ you'll get better understanding .

you can disable strictmode refer this sandbox link.it'll only render once .

https://codesandbox.io/s/snowy-violet-eo70o?file=/src/index.js

like image 27
Vyas Arpit Avatar answered Mar 21 '23 00:03

Vyas Arpit