Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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.

like image 968
bassman21 Avatar asked Nov 30 '25 01:11

bassman21


1 Answers

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.

like image 119
nilskch Avatar answered Dec 01 '25 16:12

nilskch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!