Search code examples
reactjscreate-react-appuse-state

Why does my create-react-app console.log twice?


I'm just making a simple recipe fetching app using the create-react-app setup, but when I tried logging the response it logged it twice. I went backwards and deleted code until it stopped happening and for whatever reason it starts when I use the state hook:

import React, { useState } from 'react';
import './App.css';


function App() {
  const APP_ID = '092fa53f';
  const APP_KEY = '6fcf8c591c129cc3d01aefbda0d8a4d8';
  const recipe_url = `https://api.edamam.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}`;

  const [recipes, setRecipes] = useState(0);

  return (
    <div className="App">
      {console.log('test')}
    </div>
  );
}

export default App;

Solution

  • This is on purpose, it's part of React.StrictMode (specifically to detect unexpected side effects):

    Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

    • Class component constructor, render, and shouldComponentUpdate methods
    • Class component static getDerivedStateFromProps method
    • Function component bodies
    • State updater functions (the first argument to setState)
    • Functions passed to useState, useMemo, or useReducer

    If you remove the StrictMode element from index.js, you'll see the output only gets logged once:

    ReactDOM.render(<App />, document.getElementById('root'));
    

    Note that in strict mode this only happens in development, not in production.