'Multiple XHR requests from React Component
Given the following React app, it will make two requests to the jsonplaceholder API, why does this happen and can it be prevented so it only performs one?
import { useMemo } from "react";
class Client {
constructor() {
this.setup()
}
setup = async() => {
console.log("setup")
await fetch("https://jsonplaceholder.typicode.com/todos/1")
}
}
export default function App() {
useMemo(() => { return new Client() }, [])
return null
}
https://codesandbox.io/s/currying-water-91t3in?file=/src/App.js
Solution 1:[1]
This is caused when using strict mode as react invokes certain functions twice . It also patches console.log on the second run which makes debugging hard. More information here: https://reactjs.org/docs/strict-mode.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gryevns |
