Posts > React Query Basic: Query Lifecycle

React Query Basic: Query Lifecycle

I never really created my own loading and error handling before without using React query. I know you can achieve the loading and error state using useState and useEffect but I haven’t tried it, also try catch method is also great when you want to accomplish this loading and error state for your UI.

React-query has a lot of great lifecycle methods, but I usually use the status , ( success, pending, and error or just the isLoading or isError methods ). There are lot more state to use actually but these 3 will do for achieving the loading and error state you want for your UI.

👌A query can only have 3 states pending, success and error.

Here’s how you would do it ( a straightforward use )

const { data, status } = useQuery({
	queryKey: 'movies',
	queryFn: // your fetching stuff here
})

if ( status === 'pending' ) {
	return <div> Loading data.... </div>
}

if ( status === 'error' ) {
	return <div> Error getting your data. </div>
}

return (
 <ul>
	 { data.map(() => (
		 <li>{data.name}</li>
	 ))}
 </ul>
)

So very straight forward as I said, you can get the status from your useQuery then status returnspending , success and error from your fetching method. Then just use them to generate your component as such.

isLoading

instead of using status and checking if status === 'pending' , or status === 'sucess' you can also just use isLoading which returns a boolean if your fetching is still in progress or not.

const { data, isLoading } = useQuery(
	// useQuery code here
)

isError

same with isLoading you can also use isError to check if your API fetching returns an error.

const { data, isLoading, isError } = useQuery(
	// useQuery code here
)

But why?

Sometimes our internet and server fail us and we want something to show users that there’s a delay in “loading” or there is an error on the data that they want to see. So with react-query lifecycle method can help us make sure that we make it so.