JavaScript
How to fetch data with useEffect
React hooks have been very promising solution for most of the coding issues that React framework had in old days. But for novice developers, it could be hard to understand. Especially if you are moving from old react to new. One of the main problem is how to fetch data with useEffect in a proper way.
1. Why fetch data with useEffect?
Often developers face scenarios where they need to fetch data or resolve a Promise when updating a state or prop. The savior is useEffect. To first which we should understand what is useEffect.

Above is the state machine that depicts the component life cycle.
useEffect is a different than thinking this in life cycle modal. In useEffect, an Effect is a lifecycle event.
The useEffect will be called for every lifecycle event
useEffect(() => {
console.log('Called for every lifecycle event');
});
Above code block is an example for a use Effect listening to every event. But we really don’t have a useful purpose of having a effect listener like above. Rather than that if we can specifically select the effects that we need to call the function that would be more useful.
useEffect(() => {
console.log('Called once for initial render');
return () => console.log('Called once when the component is unmounting');
}, []);
useEffect(() => {
console.log('Called every time when the state or prop is updated');
}, [stateVariable, propVariable]);
With above we can see that we cannot call an async function callback in the useEffect. Synchronous function to execute a task would make the listening to effects blocking the lifecycle flow.
2. Fetch data from useEffect
Rather than that we can execute a function that makes the async function to be executed separately, thus making the callback function not blocking the execution for an effect.
const fetchUser = userId => fetch(`https://api.example.com/user/${userId}`);
// wrong implementation
const [selectedUserId, setSelectedUserId] = useState(null);
const [userData, setUserData] = useState(null);
useEffect(async () => { // cannot use async
const userData = await fetchUser(selectedUserId);
}, [selectedUserId]);
// correct implementation
useEffect(async () => {
const fetchUserData = async () => {
const user = await fetchUser(selectedUserId);
setUserData(user);
}
}, [selectedUserId]);
// another way if you want to memoize or useCallback to initialize only once
const fetchUserData = async (selectedUserId) => {
const user = await fetchUser(selectedUserId);
setUserData(user);
};
useEffect(async () => {
fetchUserData(selectedUserId); // passing parameter incase you want useCallback
}, [selectedUserId]);
Note that both of the above examples are correct but the latter one has different benefits if you don’t want to initilize the function everytime that the effect is called.
2. Handling loading and error when fetching data
Common example is if how to show an error or how show a loading spinner when fetching data from a component.
const UserComponent = ({users}) => {
const [selectedUserId, setSelectedUserId] = useState(null);
const [userData, setUserData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(async () => {
const fetchUserData = async () => {
try {
setLoading(true);
setUserData(null); // to remove previous error
const user = await fetchUser(selectedUserId);
setUserData(user);
} catch(errorMessage) {
setError(errorMessage);
setUserData(null); // in case we need to reset state
}
setLoading(false);
}
}, [selectedUserId]);
return (
<div>
{
users.map((user) => <div key={user.userId}>{user.name}</div>)
}
{ error && <div>Error occurred while fetching data: {error}</div> }
{ loading && <div>Loading user data...</div> }
{
userData && (
<>
<h3>User Preference and Address</h3>
<div>{userData.address}</div>
<div>{userData.preference}</div>
</>
)
}
</div>
);
}
Yep, this is a way that we can do it. But its not a good coding structure. Lets try to improve this.
3. Custom hooks
We can do it by using a custom hook. To create a custom hook we need to always state the function with use name.
const useUser = (initialUser) => {
const [userData, setUserData] = useState(initialUser);
const [selectedUserId, setSelectedUserId] = useState(initialUser.userId);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(async () => {
const fetchUserData = async () => {
try {
setLoading(true);
setUserData(null); // to remove previous data
const user = await fetchUser(selectedUserId);
setUserData(user);
} catch(errorMessage) {
setError(errorMessage);
setUserData(null); // in case we need to reset state
}
setLoading(false);
}
}, [selectedUserId]);
return [{loading, error, userData}, setSelectedUserId];
}
const UserComponent = ({users}) => {
const [{loading, error, userData}, setSelectedUserId] = useUser(users[0]);
return (
<div>
{
users.map((user) => <div key={user.userId}>{user.name}</div>)
}
{ error && <div>Error occurred while fetching data: {error}</div> }
{ loading && <div>Loading user data...</div> }
{
userData && (
<>
<h3>User Preference and Address</h3>
<div>{userData.address}</div>
<div>{userData.preference}</div>
</>
)
}
</div>
);
}
Here the custom hook takes the effect updates seperately and that allows the component code to be minimum and use the atomic effect to render the component

Is that it?
Nope; there are many other ways to utilze the effects and render the components very efficiently.
- Using useReducer
- Using Suspense and lazy loading
- Using redux, recoil or any other state management framework
Also one thing to note down is there are fetch libraries that really helpful in this.
- Apollo client(GraphQL) has useQuery, useMutation hooks that gives the
loading, error, dataetc as return variables. - Libraries like useFetch which also give custom hooks for http, https requests.
Ex:const { loading, error, data = [] } = useFetch('https://example.com/todos', options, [])
Let me know what else you have discovered to make this more easy to use and scale with the code.


















117 COMMENTS
paroxetine 7.5 mg coupon
synthroid nz
albendazole drug cost zoloft 15 mg vermox uk clindamycin price
tetracycline 100 mg tetracycline 1000 mg cleocin 150 price how much is a zoloft prescription buy prednisolone uk lexapro 20mg buy singulair uk prednisolone 3 mg
concise and clean, was looking for just this kind of example thanks
[url=http://sildenafil.lol/]buy viagra soft tabs[/url]
Finally, what I’ve been waiting for has finally come after a long day has finally arrived😍😍, I hope the next chapter will come sooner
[url=https://adiflucan.online/]medication diflucan price[/url] [url=https://happyfamilypharm.online/]legitimate canadian mail order pharmacy[/url] [url=https://baclofen.click/]baclofen price in india[/url] [url=https://happyfamilyrx.quest/]canadian pharmacy 1 internet online drugstore[/url] [url=https://abilify.life/]where to get cheap abilify[/url] [url=https://canadianpharmaceuticalstores.online/]happy family store uk[/url] [url=https://buynoroxin.monster/]noroxin drug[/url]
The pellet was subjected to repeated centrifugations at 25, 000 and 10, 000 rpm, each for 15 min ovulation on clomid calculator Raven, New York
I am not on it, thank goodness where to buy cialis cheap lopressor obat omeprazole harga Employees must update their enrollment status by Aug
Thank you for another magnificent article. Where else could anyone get that kind of info in such an ideal way of writing? I have a presentation next week, and I’m on the look for such information.
This article is very informative and taught me new things about the topic.
Your article is well-researched and well-written. I appreciate the effort you put into providing valuable information to your readers.
This is a fantastic article that provides practical tips and advice. I appreciate the way you presented the information in a way that is easy to follow and relevant to readers.
I really like the way you structured this article. Your writing is clear and concise, and the information is presented in a logical and easy-to-follow manner.
Although hospitals and physician offices may face increases in price, their demand for the prescription medications used to treat their patients is also not very responsive to the price paid to manufacturers for the drug 5 can’t get erect with viagra But there is more to using anabolic steroids than just appearing to be the person you have always imagined yourself to be
I’m always impressed by the level of research and detail you put into your articles. It shows how committed you are to providing high-quality content.
Your talent for communicating complex ideas in a simple and approachable way is impressive, making your writing engaging and easy to read.
Your article has given me a lot to think about and has sparked some great discussions with my friends and family. Thank you for providing such thought-provoking content.
Bonferoni, M buy cialis online us Greenberg PL, The Myelodysplastic Syndromes, in Hoffman R, et al
Your ability to break down complex ideas into simple, easy-to-understand language makes the information more accessible.
Your article was informative and easy to read. Thank you for presenting the information in a way that’s easy to understand.
w2tkq0
Your writing style is exceptional. I enjoyed reading this article and appreciated the way you presented the information in an engaging and thought-provoking manner.
Your article is a great resource for anyone interested in this topic. I’m grateful for the time and effort you put into creating it.
I am very impressed with the knowledge and insights you shared in this article. Your writing style is engaging and easy to follow.
Your writing is so engaging and well-written. It’s clear you have a talent for crafting compelling content.
Your attention to detail and thorough research is evident in this article. I appreciate the time and effort you put into creating such a comprehensive piece.
Your article is a valuable resource for anyone interested in this topic. I’ve already shared it with several friends and colleagues.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
La weekly There is definately a lot to find out about this subject. I like all the points you made
Fourweekmba Good post! We will be linking to this particularly great post on our site. Keep up the great writing
Your article helped me a lot, is there any more related content? Thanks!
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Your article helped me a lot, is there any more related content? Thanks!
Thinker Pedia Good post! We will be linking to this particularly great post on our site. Keep up the great writing
FinTechZoomUs Great information shared.. really enjoyed reading this post thank you author for sharing this post .. appreciated
FinTechZoomUs very informative articles or reviews at this time.
Your articles are extremely helpful to me. Please provide more information!
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article.
Mountsinai I like the efforts you have put in this, regards for all the great content.
Your article helped me a lot, is there any more related content? Thanks!
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://www.binance.com/join?ref=P9L9FQKY
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Your article helped me a lot, is there any more related content? Thanks!
UID_53166217###
Yuk, lihat info terkini seputar stok elpiji 3 kg di Batu, cek di sini, teman-teman! 📢🔥 Info Stok Elpiji 📰👈 Jangan sampai kehabisan ya! 😊🙏
Dapatkan info terbaru dari Berita Dana terbaru setiap harinya.
UID_72331432###
tess111
UID_59407105###
berita dana x twitter viral berita dana desa ada disini !
UID_72942561###
Berita Hot! 🔥🔥 Isa Rachmatarwata Tersangka Kasus Jiwasraya Buntut kerugian negara hingga 16,8 Triliun! 😲😲
UID_53550706###
Berita terbaru! 🔥 Isa Rachmatarwata Ditahan Kejagung dalam kasus Jiwasraya. 🚔👮♂️
UID_57092237###
Berita gembira! 🎉 Pasokan Gas 3 Kg di Kramat Jati Kembali Normal 🎊 Siap-siap belanja gas, ya! 💪🔥
UID_72339950###
Heboh! 📣🔥 Unjuk Rasa di Polda Jatim 📢 Menuduh Jokowi Terlibat Korupsi! 😱🔍
UID_27764099###
Ini yang di ganti >>> “Bingung Kenapa 😕❓” Federasi Sepak Bola Pakistan Disanksi FIFA “Baca Penyebabnya Disini! 🧐🔍”
UID_74743238###
Ini dia! 🎉🎉 ASN BKN Ubah Pola Kerja yang baru dan efisien! 🎉🎉.
UID_83344528###
Inilah 🎉🎉 Pupuk Inovatif Kebun Riset Kujang yang bikin Wamen BUMN bangga! 💪🏻🇮🇩
UID_95859078###
Baru-baru ini, para pemain Mahjong Wins 3 dikejutkan dengan bocoran RTP yang diklaim bisa meningkatkan peluang kemenangan secara signifikan. Banyak yang percaya bahwa informasi ini membantu mereka mendapatkan hasil yang lebih konsisten dalam permainan. Jika Anda ingin tahu lebih lanjut, cek bocoran RTP Mahjong Wins 3 hari ini dan lihat apakah strategi ini benar-benar efektif.
UID_17136916###
Kisah inspiratif datang dari seorang tukang ojek online asal Tangerang yang berhasil membawa pulang hadiah fantastis setelah bermain Mahjong Ways 2. Dengan modal kecil, ia sukses mengubah nasibnya dan meraih kemenangan besar senilai 200 juta rupiah. Penasaran bagaimana caranya? Simak kisah lengkapnya di artikel tukang ojek online menang 200 juta dari Mahjong Ways 2.
UID_87427935###
Cek yuk! 🚍👮♂️Operasi Keselamatan 2025 Polres Ciamis Siapa tahu bus favoritmu jadi sasaran! 😱👍
UID_18563832###
Ini yang di ganti >>> Yuk, ketahui lebih lanjut tentang Syarat Gabung OECD dan Pentingnya Ratifikasi Konvensi Antisuap di sini! 🕵️♀️🔎📚.
UID_83003169###
Kenalan yuk! 🤝 Dengan guru inspiratif ini, Guru Dede Sulaeman yang mengajarkan cara merapikan pakaian di kelasnya. 👕👚🎓
UID_97211224###
Yuk, sehat bersama! 👨⚕️👩⚕️ Cek kondisi tubuh kamu di Program Cek Kesehatan Gratis sekarang juga! 💉🌡️ Selalu jaga kesehatan, ya! 🏥💖
Your article helped me a lot, is there any more related content? Thanks!
amduRQJED45
dfglCEBv3eu
LYaTpS7bzL5
aOAmnzPFNxI
JuIiYtTAEvi
Avm1fKRr4mO
0MMaelaMHdP
4cO7TFuD70p
BDOjaFops6A
3MmiLDy93Ds
YhrJl0zFND2
sj6FPcKXw4o
zh8ciOTgFpD
dLNDwsmxmev
r9H0wJKQE4o
8Ze0DapiiUf
03Sje6cJgxc
6dub8jm6dcz
C5c83wyGWpT
ZjXdHiRflR5
4ycRcFi2VKo
3hY5bjK0P7q
CGECwSCOomS
i3dAb8vLHe0
L1ftunFjOuW
gk6y6XLImw5
8cE8rGqsjsR
nWTlNRRkGhL
LgmWrDSeTcg
dswcaN78Yyj
IAdSSMotVmK
oJDJydhaNvh
CvnUq3uM7Ch
CR0jeY2MDEw
J19RC1hcQjr
Your article helped me a lot, is there any more related content? Thanks!
ls7v8h
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
hentaifox There is definately a lot to find out about this subject. I like all the points you made
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Your article helped me a lot, is there any more related content? Thanks!
Thanks for sharing. I read many of your blog posts, cool, your blog is very good.
oxffue
lszzvo
Thank you for writing this article. I appreciate the subject too. http://www.hairstylesvip.com
rmdq2y
Hello mates, its wonderful post on the topic of cultureand entirely explained, keep it up all the time.
Hello mates, its wonderful post on the topic of cultureand entirely explained, keep it up all the time.
If you’re looking for a new place to play, 615betwin is worth checking out. They’ve got a solid selection and the site runs smoothly. Nothing too flashy, but gets the job done. See if you can win: 615betwin