bassman21
bassman21

Reputation: 380

Why is my (super simple) React component initially always rendered twice?

I am working on some optimization algorithms in the context of a larger React project. While testing some things I have encountered the following behavior of React: Even the most simple React component is initially always rendered twice. I am wondering why.

Here is my source code that demonstrates this behavior:

App.tsx

import React from 'react';
import './App.css';
import Test1 from './components/Test1';

function App() {
  return <Test1 />;
}

export default App;

Test1.tsx

import React, { useEffect, useRef } from 'react';

const Test1 = () => {
  // useRef hooks
  const counter: React.MutableRefObject<number> = useRef<number>(0);

  // useEffect hooks
  useEffect(() => {
    counter.current++;
    console.log(counter.current.toString());
  }, []);

  return <div>Test1</div>;
};

export default Test1;

counter.current is initially always increased to 2.

Upvotes: 3

Views: 145

Answers (2)

nilskch
nilskch

Reputation: 426

It is because of the React.StrictMode. Updating the Ref forces the component to re-render. See React Hooks: useEffect() is called twice even if an empty array is used as an argument for further information.

Upvotes: 4

bassman21
bassman21

Reputation: 380

Many thanks to those who commented super quickly and pointed out that this is expected behavior from React's "Strict Mode"!

I can confirm that this is the right answer to my question.

I have just run a production build that does not show this behavior any more. I only get one "console.log" and the counter only increase once.

Upvotes: 2

Related Questions