2

I have created a basic create-react-app and added the below statement

const [stateA, setStateA] = useState(false); 

and I have put a console.log inside my component. The complete component code is

import React, { useState } from 'react'; import logo from './logo.svg'; import './App.css'; const App = () => { const [stateA, setStateA] = useState(false); console.log("rendered"); return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App; 

It is showing "rendered" twice. Can any one tell why this is happening ?

1
  • React can render your components more than once when running in dev mode, also you might be using the StrictMode component which rendering components multiple times to catch side effects inside renders Commented Apr 8, 2020 at 15:13

1 Answer 1

2

If you notice index.js (as create-react-app now uses React.StrictMode by default ) file you may have a wrapper called React.StrictMode which is responsible for this extra re-render. The wrapper will invoke render, constructor and other lifecycle methods to detect side effects. So this is expected.

You can read more here: https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.