I know the conventional way when using hooks is to fetch the data using the useEffect
hook. But why can't I just call axios in the functional component instead of a hook and then set the data.
Basically, I am asking what is wrong with doing this:
const [users, setUsers] = useState(null);
axios.get("some api call")
.then(res => setUsers(res.data))
Here, I do not use useEffect
, what could go wrong?
Making a request and changing the state on render like that will cause the component to re-render forever.
Every time the component renders, eg due to props changing or due to hooks changing , that axios.get
request gets called. When it gets a response, it will update the state. Then, because the state has changed, the component re-renders, and axios.get
is called again. And the state changes again, and the request is made again, forever.
Prefer useEffect(() => code... , [])
.
That said, you can also do it while avoiding an infinite loop but it's a very bad practice and I don't recommend it.
Yes, you will have a re-render but you won't have an infinite loop. Use useState's lazy init function .
const [users, getUsers] = useState(() => {
axios.get("some api call")
.then(res => getUsers(res.data))
});
Best practice is:
const [users,getUsers]= useState();
useEffect ( () => {
axios.get("some api call")
.then(res=>getUsers(res.data))
}, []);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.