In ReactJS, you can create a loading page state to indicate to users that the application is in the process of loading data or performing an operation. Here's a basic example of how you can implement a loading page state in React:
import React, { useState, useEffect } from 'react';
function App() {
const [loading, setLoading] = useState(true); // State to track loading status
useEffect(() => {
// Simulate data loading delay with setTimeout
const loadData = () => {
setTimeout(() => {
setLoading(false); // Set loading state to false after delay
}, 2000); // Simulated loading time: 2000 milliseconds (2 seconds)
};
loadData(); // Call loadData function when component mounts
}, []); // Empty dependency array to run effect only once on mount
return (
<div>
{loading ? (
<div>Loading...</div> // Render loading message when loading state is true
) : (
<div>Loaded successfully!</div> // Render content when loading state is false
)}
</div>
);
}
export default App;
In this example:
- We use the
useState
hook to manage the loading state, initializing it astrue
. - We use the
useEffect
hook with an empty dependency array to simulate data loading. This effect runs only once when the component mounts. - Inside the
useEffect
, we simulate a loading delay withsetTimeout
. After the delay, we update the loading state tofalse
. - In the return statement, we conditionally render a loading message or the content based on the value of the
loading
state.
You can customize the loading message and loading time according to your requirements. Additionally, you can enhance this example by replacing the simulated loading with actual data fetching or other asynchronous operations.
Top comments (0)