Reputation: 3993
When I make a request through axios outside useEffect, it triggers twice, even when there is no other rendering happening on the page?.
Note that only axios is triggered twice, not the regular console.log
The complete code is as follows:
import axios from "axios";
function App() {
console.log('only once') // this is triggered only once
axios.get('https://jsonplaceholder.typicode.com/users')
.then(res => {
console.log(res)
})
return (
<>
<h2>Testing Axios</h2>
</>
);
}
export default App;
The output is like this:
Please help me understand why this happens like this? And it works fine when placed in useEffect, why would that make a difference as we are not changing anything in DOM anyway?
Thanks.
Upvotes: 1
Views: 2068
Reputation: 169051
Because my crystal ball says your component is wrapped in React.StrictMode
(likely in your ReactDOM.render
call).
Strict Mode calls your component functions twice on purpose so you would know if you had side effects in them (and React would know if state or render results changed based on those side effects or state outside of the component, and it would loudly complain).
Don't do side effects without useEffect
.
Upvotes: 3