Reputation: 119
I am trying to build a simple To\Do app with react and the homepage is a list of notes that are saved in dummy_data.js as json objects. when I try to console.log something in component NotesList, it prints twice in the console. And it is not intended to happen. Running once is required.
App.js
import React from 'react';
import NotesList from './pages/NotesListPage';
import Note from './pages/NotePage';
import Header from './components/Header';
import {
BrowserRouter as Router,
Routes,
Route
} from 'react-router-dom';
function App(){
return(
<div>
<Router>
<Header />
<Routes>
<Route path='/' element={<NotesList />} />
<Route path='/note/:id' element={<Note />} />
</Routes>
</Router>
</div>
);
}
export default App;
NotesListPage.js
import notes from '../assets/dummy_data';
import ListItem from '../components/ListItem';
function NotesList(){
console.log('am i running twice?')
return(
<div>
{
notes.map((note, index) =>(
<div key={index}>
<ListItem note={note} />
<br/>
</div>
))
}
</div>
);
}
export default NotesList;
ListItem.js
import {Link} from 'react-router-dom';
function ListItem(props){
//console.log(props)
return(
<Link to={`/note/${props.note.id}`}>
<i>{props.note.body}</i>
</Link>
)
}
export default ListItem;
dummy_data.js
let notes = [
{
"id": 1,
"body": "Todays Agenda\n\n- Walk Dog\n- Feed fish\n- Play basketball\n- Eat a salad",
"updated": "2021-07-14T13:49:02.078653Z",
"created": "2021-07-13T21:54:16.235392Z"
},
{
"id": 2,
"body": "Bob from bar down the \n\n- Take out trash\n- Eat food",
"updated": "2021-07-13T20:43:18.550058Z",
"created": "2021-07-13T00:17:13.289897Z"
},
{
"id": 3,
"body": "Wash car",
"updated": "2021-07-13T19:46:12.187306Z",
"created": "2021-07-13T00:16:22.399841Z"
}
]
export default notes;
when I try to do console.log(props) in ListItem, same thing happens. Can someone tell me what could be the reason for that?
Upvotes: 1
Views: 1072
Reputation: 4383
this behavior might be because StrictMode whitch renders components twice
(on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).
if you don't want it to do so you can disable StrictMode by removing the <React.StrictMode>
tag in the index.js
:
change :
ReactDOM.render(
<React.StrictMode>
<app/>
</React.StrictMode>,
document.getElementById('root')
);
to :
ReactDOM.render(
<app/> ,
document.getElementById('root')
);
Upvotes: 3