I have a question about how to manage state in a React apps. What I have been accustomed to doing is something like this – some of this is pseudocode:
Home.js
const LOADING_TIMEOUT_CONSTANT = 1000
import React, { useState, useEffect } from "react";
export default function Home(){
const [loaded, isLoaded] = useState(false);
const results = getData();
useEffect(()=> {
// wait for results to fetch from server
setTimeout(() => {
isLoaded(true)
}, LOADING_TIMEOUT_CONSTANT)
}, [])
return (
<div>
{!loaded ? <p>Loading ....</p> : <p>Homepage Content Here</p>}
</div>
)
}
This however, seems a bit clunky to me and I’m not clear on best practices. Is this the standard, or are there other ways to manage this type of conditional display based on loading states or just any asynchronous fetching?
Thanks!
Tried searching stackoverflow, looking up youtube videos, searching reddit, etc. but I’m more looking into what the overall standard is for react developers.
4
Answers
I guess there isn’t a best practice to things in developers world, but instead of relying on a
setTimeout()
, I tend to manually assign states usingtry..catch..finally
like:This is other ways to manage this type of condition
One of the nice and easy-to-learn conventions you could follow is using
React Query
withAxios
for asynchronous data fetching:For example (more details on https://www.copycat.dev/blog/react-query/):
React Query
basically gives you theuseQuery
hook that returns a handful of objects such asisLoading, data, error, refetch
, etc. These objects will help you check different states and render output accordingly.Axios
helps you to fetch/send data using promises.To learn about more advanced usage of these tools, check out their docs:
https://github.com/axios/axios
https://tanstack.com/query/latest
You need to make some changes so that loading state can be updated when getData request completes.