3

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.

bassman21
  • 320
  • 2
  • 11
  • What do you mean by "render twice"? Are there two elements in the DOM or two `console.log`? – Lars Jul 20 '22 at 08:25
  • 1
    Are you using react strict mode? If so, this is expected behavior from React's Strict Mode - https://reactjs.org/docs/strict-mode.html . More details can be found in the blog post for React v18 here: https://reactjs.org/blog/2022/03/29/react-v18.html – nbokmans Jul 20 '22 at 08:26
  • Maybe possible beacuse of the strict mode in development. [Check this](https://reactjs.org/docs/strict-mode.html) – Tirth Trivedi Jul 20 '22 at 08:26
  • To answer the first question: Yes, I do always get two "console.logs". – bassman21 Jul 20 '22 at 08:27
  • So, I guess what's the point of @widepeepohappy that it does not "render twice", just render once and then it re-renders, which is desired in that case :) – Alan Jul 20 '22 at 08:33

2 Answers2

4

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.

nilskch
  • 307
  • 3
  • 10
2

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.

bassman21
  • 320
  • 2
  • 11