Home > front end >  Why my component is rendering 6 times, two for each data change?
Why my component is rendering 6 times, two for each data change?

Time:10-07

So I'm trying to get a data from an API in the first rendering of the component, but I don't exactly know why the component is rendering 6 times, two times for each data change. Shouldn't the useEffect execute once?

App.js:

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

function App() {

  const [words, setWords] = useState()

  useEffect(()=>{
    const requestRandomStringFromAPI = async () => {
      const response = await fetch('https://catfact.ninja/fact')
      const { fact } = await response.json()
      const threeFirstWords = fact.split(' ', 3).join(' ')
      setWords(threeFirstWords)
    }

    requestRandomStringFromAPI()
  }, [])

  console.log(words)

  return (
    <div className="App">
      <h1>{words}</h1>
    </div>
  );
}

export default App;

This is the average output on console:

App.js:19 undefined
App.js:19 undefined
App.js:19 The longest living
App.js:19 The longest living
App.js:19 Statistics indicate that
App.js:19 Statistics indicate that

CodePudding user response:

I think wrapping your app <React.StrictMode> causing this. Strict mode and React Developer Tools extension can render your component multiple times for debugging. This won't happen in a production build.

CodePudding user response:

It's probably because of React@18 Strict mode :

If you are seeing this code In your App.js Strict Mode is activated :

<React.StrictMode>
<App />
</React.StrictMode>

For fixing the problem remove React.StrictMode component from your code.

  • Related