logologo

Three-D

☕Sign in

    Recent Post:

    Categories:

    nextjsjavascriptthreejshonoreactjs
    featured post image

    snippets

    featured post image

    What is Currying?

    featured post image

    What is an IIFE?

    Managing Loading, Error, and Layout Pages in Next.js

    July 1, 2024

    462

    image

    Think you know it all?

    Take quiz!

    Next.js provides robust support for managing different aspects of the user experience, including loading states, error handling, and layout design. Here's how you can implement these features:

    1. Loading Page

    A loading page or component is crucial for providing feedback to users while data is being fetched. You can create a simple loading component and use it in your pages.

    code

    // components/Loading.js
    
    export default function Loading() {
     return <div>Loading...</div>;
    }
    
    // pages/index.js
    import { useState, useEffect } from 'react';
    import Loading from '../components/Loading';
    
    export default function HomePage() {
     const [data, setData] = useState(null);
     const [loading, setLoading] = useState(true);
     useEffect(() => {
      fetch('/api/data')
       .then((response) => response.json())
       .then((data) => {
        setData(data);
        setLoading(false);
       });
     }, []);
     if (loading) return <Loading />;
     return (
      <div>
       {' '}
       <h1>Home Page</h1> <pre>{JSON.stringify(data, null, 2)}</pre>{' '}
      </div>
     );
    }

    2. Error Page

    Next.js allows you to create custom error pages by using a file named _error.js inside the pages directory. This page will render whenever there is a server-side or client-side error.

    code

    // pages/_error.js
    
    function Error({ statusCode }) {
     return <p> {statusCode ? `An error ${statusCode} occurred on server` : 'An error occurred on client'} </p>;
    }
    Error.getInitialProps = ({ res, err }) => {
     const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
     return { statusCode };
    };
    
    export default Error;

    3. Layout Page

    Using layout components helps in maintaining consistent structure across different pages. You can create a layout component and wrap your pages with it.

    code

    // components/Layout.js
    
    export default function Layout({ children }) {
     return (
      <div>
       {' '}
       <header>Header</header> <main>{children}</main> <footer>Footer</footer>{' '}
      </div>
     );
    } // pages/index.js
    import Layout from '../components/Layout';
    export default function HomePage() {
     return (
      <Layout>
       {' '}
       <h1>Home Page</h1> <p>Welcome to our website!</p>{' '}
      </Layout>
     );
    }

    By effectively managing loading states, errors, and layouts, you can enhance the user experience and maintain a clean, organized codebase in your Next.js application.