Communication between client and server is required to fetch data from APIs. This process may take time, so a loader must be shown to the user that the process needs to wait until it is resolved.
Why is this necessary? because if no visual feedback is given to the users, they might think that your application is not responding or stuck. This User Experience (UX) becomes important to tell the user about the system's current state.
In the front end especially React, we can give the experience to the user about this process using state.
Usually, React developers use a state to indicate whether the APIs have been resolved.
import { useState } from 'react';
const [isLoading, setIsLoading] = useState(false);
const APICaller = async () => {
try{
// show loading to users
setIsLoading(true);
const response = await API.call_end_point();
// handle response
} catch (error) {
// handling error
} finally {
// hide loading whenever the process has been completed
setIsLoading(false);
}
}
By default, React will re-render the component when the state is updated, with the previous code at least the component is re-render 3 times.
Initial render, this process mounts the component and calls the API (first mounting).
Show loading to a user, this process is updated on isLoading value becomes true.
Hide loading, because the process has been completed.
this is the natural process of React.
What we can do is simplify our code, they don't need to handle too many states (stateless).
Statesless to handle a loading state.
API calls may be triggered by page load or actions (clicking a button, typing an input, etc). It will have a different approach based on the user trigger, let's dive into it.
Page Load.
This is an action to load and display all its content in the user's browser, from the initial request to the final rendering. With this action, your web is possible to load data from API, to serve the data using stateless we can utilise lazy and suspense from React. Why is this possible? suspense
behaviour is showing the fallback until the children component has finished.
const LazyComponent = lazy(() => FetchData().then((data) => ({
default: () => <div>{JSON.stringify(data)}</div>
})));
export default function StatelessLoadingPage () {
return (
<Suspense fallback={<p>Loading...</p>}>
<LazyComponent />
</Suspense>
)
};
Result:
Actions.
Action can be triggered by clicking a button, or changing a value in the input element. Have a different approach from Page Load, this approach will utilise useTransition. This hook lets you render a part of the UI in the background.
import { useTransition } from 'react';
export default function TransitionLoadingPage () {
const [isPending, startTransition] = useTransition();
const onClick = () => {
startTransition(async() => {
const data = await FetchData();
console.log(data);
});
};
return (
<div>
<button onClick={onClick} disabled={isPending}>
{isPending ? 'Loading': 'Click me!'}
</button>
</div>
)
};
Conclusion
This is not the only way to handle stateless in terms of waiting an API calls, You can utilise other hook functions like use or anything that keeps your code simple. You can find my code here.
Hope you found this helpful!
Cheers 🍻
Top comments (0)