How to Implement React Loading Skeleton?
Learn how to implement React Loading Skeleton with best practices.
import axios from "axios";
import { useEffect, useState } from "react";
import Skeleton from "react-loading-skeleton";
import "react-loading-skeleton/dist/skeleton.css";
const YourComponent = () => {
const [loading, setLoading] = useState(false);
const [data, setData] = useState([]);
const getSomething = async () => {
try {
setLoading(true);
const { data } = await axios.get(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/yourApiEndPoint`
);
setData(data); // Set the fetched data in the state
setLoading(false);
} catch (error: any) {
setLoading(false);
console.error(error.response.data.message || "An error occurred.");
}
};
useEffect(() => {
getSomething();
}, []);
return (
<div>
{loading ? (
<div className="">
<Skeleton
count={5} // You get 5-line skeleton
baseColor="#ffffff" // The color from gradient starts
highlightColor="#9ca3af" // Second gradient color
className="h-[100px]" // You can specify your own styles here
circle={true} // Makes the skeleton circular
/>
<Skeleton
highlightColor="#9ca3af"
baseColor="#ffffff"
// If you dont specify height it will be the height of default text
/>
</div>
) : (
<div>{/* Whatever is fetching from server */}</div>
)}
</div>
);
};
export default YourComponent;
We use React hooks to define two pieces of state: loading and data.
The loading state variable is used to keep track of whether the data is being loaded or not, and setData is a function used to update the data state variable.
The getSomething function
is an asynchronous function that performs an HTTP GET request to retrieve data from the server. It first sets the loading state to true to indicate that data is being fetched. Then it uses the axios.get method to send a GET request to the specified API endpoint. The response data is extracted and stored in the data state using the setData function. Finally, the loading state is set back to false to indicate that data fetching is complete. If an error occurs during the request, the catch block is executed, setting the loading state to false and logging the error message to the console.
The useEffect hook
is used here to trigger the getSomething function when the component mounts. The [] passed as the second argument ensures that the effect runs only once, similar to the componentDidMount lifecycle method in class components.
Finally, the component's JSX code
is defined within the return statement. If loading is true, a loading animation using the Skeleton component is rendered. It displays a placeholder skeleton with five lines and a height of 100 pixels. The skeleton has a white base color and a highlight color of #9ca3af. Additionally, there is a circular skeleton specified by the circle prop. If loading is false, the actual fetched data or any other desired content can be rendered.