DEV Community

Cover image for Implementing a Loading Page State in ReactJS: Enhancing User Experience with Loading Indicators
mandeepsng
mandeepsng

Posted on

Implementing a Loading Page State in ReactJS: Enhancing User Experience with Loading Indicators

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;
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We use the useState hook to manage the loading state, initializing it as true.
  • 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 with setTimeout. After the delay, we update the loading state to false.
  • 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)