To enhance the user experience, we can preload the new page component while keeping the current page displayed. We’ll use React.lazy for lazy loading, but instead of using React.Suspense directly in the route, we’ll manage the loading state manually within the home component. Here’s how:
1. Set up State and Navigation: We introduce a loading state in the home component to manage the loading status and use the useHistory hook from React Router to navigate programmatically.
2. Preload the Page Component: When the link is clicked, we prevent the default behavior, set the loading state to true, and preload the Page component using import. Once the component is preloaded, we reset the loading state and navigate to the new route.
import React, { useState } from "react"; import { BrowserRouter as Router, Switch, Route, Link, useHistory, } from "react-router-dom"; const Page = React.lazy(() => import("./Page")); const Home = () => { const [loading, setLoading] = useState(false); const history = useHistory(); const navigateToPage = async (event) => { event.preventDefault(); // Prevent default link behavior setLoading(true); await import("./Page"); // Preload the page component setLoading(false); history.push("/page"); // Navigate to the new page }; return ( <div> <h1>Home</h1> <Link to="/page" onClick={navigateToPage}> Go to another page </Link> {loading && <div>Loading page...</div>} </div> ); }; const App = () => { return ( <Router> <Switch> <Route exact path="/" component={Home} /> <Route path="/page"> <React.Suspense fallback={null}> <Page /> </React.Suspense> </Route> </Switch> </Router> ); }; export default App;
1. State and Navigation: In the Home component, we define a state variable loading to track whether the new page is being preloaded. The useHistory hook allows us to navigate programmatically.
2. Preloading and Navigation: When the user clicks the link, the navigateToPage function is triggered. This function:
3. Rendering: The App component sets up the routes using React Router. The home route renders the Home component. The /page route uses React.Suspense with a null fallback, ensuring that the loading state is managed within the Home component rather than showing a separate loading message.
This approach keeps the current page visible with a loading message until the new page is fully loaded, enhancing the user experience by providing a smooth transition between pages.