Since the data can be fetched without using useEffect()
hook, directly from axios, then why it is preferred to use useEffect()
and then axios?
Also, in which case useEffect()
is not required?
Here is an example:
useEffect(() => {
axios
.get('http://localhost:3001/notes')
.then(response => {
setNotes(response.data)
})
}, [])
By using useEffect
, you tell React that your component needs to do something after render. React will remember the function you passed, and call it later after performing the DOM updates.
You use React Hooks when using a Functional Component, while using a Class-Based component you can use axios
in the componentDidMount()
method to fetch data from the API.