-1
import React, {useState, useEffect} from 'react'

export function UseStateExample() { // named export, need to use the same name everywhere nad {} when importing/exporting.
  const [resourceType, setResourceType] = useState(null)

  useEffect(() => {
    fetch(`https://jsonplaceholder.typicode.com/${resourceType}`)
      .then(response => response.json())
      .then(json => console.log(json))
  }, [resourceType])

  // useEffect(() => {s
  //   console.log('On Mount, since it is an empty array')
  // }, [])

  return (
    <>
      <div>
        <button onClick={() => setResourceType('posts')}>Posts</button>
        <button onClick={() => setResourceType('users')}>Users</button>
        <button onClick={() => setResourceType('comments')}>Comments</button>
      </div>
      <h1>{resourceType}</h1>
    </>
  )
}

Apparently, the useEffect hook should run only once. But when I check the console after reloading the page, I see that the fetch request runs twice.

Konrad
  • 21,590
  • 4
  • 28
  • 64
Phukon
  • 21
  • 4
  • 1
    This is NOT Java. – Sören Mar 06 '23 at 20:41
  • Does this answer your question? [React Hooks: useEffect() is called twice even if an empty array is used as an argument](https://stackoverflow.com/questions/60618844/react-hooks-useeffect-is-called-twice-even-if-an-empty-array-is-used-as-an-ar) – Konrad Mar 06 '23 at 21:07
  • Most likely you have the strict mode turned on – Konrad Mar 06 '23 at 21:07

1 Answers1

1

I think this is happening because React.StrictMode is enabled in your react application. See this answer. To disable StrictMode go to your index.js file and remove or comment next 2 lines:

  // <React.StrictMode> remove or comment this tag
       <App />
  // </React.StrictMode> and this tag

and re-run your application.