5

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;
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
pshaw20
  • 103
  • 2
  • 7
  • You should have removed the 3 unused `const`s - now you need to rotate those credentials. – jonrsharpe Apr 30 '20 at 10:55
  • 1
    Does this answer your question? [Why does useState cause the component to render twice on each update?](https://stackoverflow.com/questions/61578158/why-does-usestate-cause-the-component-to-render-twice-on-each-update) – jonrsharpe May 14 '20 at 15:01

1 Answers1

17

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437