reactjs

How to have a loading screen until all my components are mounted in React


I do not have any API calls for my react app, I want to have a loading page while all my components are being mounted (including all children). My page does take few seconds to load.

The issue I am having is that I do not want to use setTimeout as my page can load for any amount of seconds. I just want to show a loading screen until my actual page is ready to show.


Solution

  • Try the load event like so (assuming you're talking about react hooks implementation.) :-

    const Component = () => {
    const [isLoading, setIsLoading] = React.useState(true);
    
    const handleLoading = () => {
    setIsLoading(false);
    }
    
    useEffect(()=>{
    window.addEventListener("load",handleLoading);
    return () => window.removeEventListener("load",handleLoading);
    },[])
    
    return !isLoading ? (
    {*/ your content here */}
    ):({*/ your loader */})
    
    }