How to fetch data without useEffect hooks in React function component?
Asked Answered
U

4

9

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?

Undertow answered 27/5, 2020 at 19:6 Comment(1)
It will be called every time the component renders (e.g. props change, hook state changes). Try it. That will give you an infinite loop, since every time you update the state with getUsers, it'll re-render, triggering another request, triggering another render, ...Lave
L
4

Making a request and changing the state on render like that will cause the component to re-render forever.

Every time the component renders, e.g. 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.

Lave answered 27/5, 2020 at 19:20 Comment(0)
C
3

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))
});

Cloy answered 27/5, 2020 at 19:24 Comment(1)
This is a good concept. However, it would go into bottlenecks handing error with your http requestClaypan
Q
0

I dont believe that useEffect is the best practice. it will actually call it twice if on strict mode. the solution for this is use useQuery library.

Quoin answered 1/3 at 13:31 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Suburbanite
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewAlfreda
B
-1

Best practice is :

const [users,getUsers]= useState();
useEffect ( () => {
   axios.get("some api call")
  .then(res=>getUsers(res.data))
}, []);
Bactria answered 27/5, 2020 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.