AllTechnologyProgrammingWeb DevelopmentAI
    CODING IS POWERFUL!
    Back to Blog

    Nextjs React

    15 min read
    January 18, 2025
    Nextjs React

    Next.js 13 Intro

    Next.js 13 brings significant improvements and new features aimed at enhancing both developer experience and application performance. Let's explore some of the key highlights.

    Initial Page Loads

    With the new architecture, Next.js 13 drastically improves initial page load times. This is achieved through various optimizations including:

    • Optimized server-side rendering (SSR)
    • Efficient code splitting
    • Enhanced static site generation (SSG)

    These improvements lead to a snappier experience for users, especially on the first visit to your site.

    Router Cache

    The new router cache significantly reduces client-side data fetching for subsequent page navigations. This means that if the data for a page hasn't changed, Next.js will use the cached data. This feature improves the performance and user experience drastically by reducing unecessary network requests.

    How does the router cache work? Next.js utilizes a local browser storage to store the route information. On subsequent navigations, Next.js will check to see if the route is available in the cache. If it is, then the data is used from the cache instead of going to the server.

    Here is a simple example, where we can see the benefits of Router Cache:

                
    import { useState, useEffect } from 'react';
    
    function MyPage() {
      const [data, setData] = useState(null);
    
      useEffect(() => {
        const async fetchData = async () => {
          const response = await fetch('/api/data');
          const result = await response.json();
          setData(result);
        };
        fetchData();
      }, []);
    
    
      return (
        <div>
            {data ? <h2> Data is loaded </h2> : <h2> Loading... </h2> }
        </div>
      );
    }
    
    export default MyPage;
                
              

    Loading UI

    Next.js 13 introduces built-in support for loading UI states. This improves the user experience during initial page load and transitions between pages. You can now easily show a loading indicator or skeleton UI until the actual page content is ready.

    How to use the Loading UI? With Next.js 13, creating a loading UI is seamless, you can create a `loading.js` or `loading.tsx` file within a specific route. This component will be displayed automatically when the route is loading. Here is a basic example:

             
    export default function Loading() {
      return <div> Loading... </div>
    }
             
             

    This loading UI would be displayed if the route `your-website.com/profile/settings` is loading. The page will display the component in `profile/settings/loading.js` until the actual page is completely loaded. This creates a seamless user experience.

    Improved UX

    All the changes in Next.js 13 collectively contribute to an improved user experience. Faster page loads, reduced loading times and seamless transitions make applications built on this framework more enjoyable and efficient. These features enable developers to provide a more polished, performant and user-friendly web application.

    Initial Page Loads

    Understanding initial page load performance is crucial for creating a smooth user experience. This section dives into the details of how Next.js 13 handles this critical aspect.

    What Happens During Initial Load?

    When a user first visits your Next.js application, there's a sequence of events that occurs. Let's explore these key steps:

    • Server-Side Rendering (SSR): Next.js primarily uses SSR for the initial page load. This means the HTML is generated on the server, providing the user with fully rendered content faster than client-side rendering alone.
    • HTML Delivery: The server sends the pre-rendered HTML to the user's browser. This allows the user to see content immediately, improving perceived performance.
    • Hydration: Once the HTML is delivered, React takes over the page, making it interactive. It 'hydrates' the static HTML by attaching event listeners and enabling dynamic updates.
    • Client-Side Navigation: For subsequent navigation, Next.js uses client-side routing, making page transitions faster and smoother.

    Key Factors Affecting Initial Page Load

    Several factors influence the speed of initial page loads in Next.js. Understanding these factors helps in optimization.

    • Server Response Time: How quickly your server processes the request and returns the HTML directly impacts the page load time. Optimize database queries, APIs, and server resources.
    • Bundle Size: The amount of JavaScript, CSS, and other assets needed for the application will affect the load time. Minimizing bundle sizes is very crucial.
    • Large Images and Resources: Big images or unoptimized resources significantly impact initial load. Implement image optimization, lazy loading, etc.

    Optimizing Initial Page Load

    Here are some key strategies to optimize initial page loads:

    • Code Splitting: Divide the application into smaller chunks. Only load the JavaScript needed for the current page.
    • Lazy Loading: Load images and other resources only when they are needed or visible.
    • Image Optimization: Reduce the sizes of images by compressing them, using the correct format like WebP and responsive image implementation.
    • Caching: Implement caching strategies on the server and browser to reduce the load.

    Example: Lazy loading of components

    Here is an example of how you can implement lazy loading.

            
            import { lazy, Suspense } from 'react';
            
    const LazyComponent = lazy(() => import('./MyComponent'));
    function MyPage() {
    return (
    <div>
    <h1>My Page</h1>
    <Suspense fallback={<div>Loading...</div>}>
    <LazyComponent />
    </Suspense>
    </div>
    ); }
    export default MyPage;

    Remember to optimize your app.

    Router Cache

    Next.js 13 introduces a powerful router cache, significantly improving navigation performance. This cache stores the results of server-side data fetches and rendered components for each route. When you navigate back to a page or route, Next.js can reuse the cached content if no change occurred, bypassing the need for a fresh data fetch and server render.

    How Router Cache Works

    The router cache operates both on the client and the server side. The client-side router cache lives within the browser and helps with instant back button navigation. The server-side cache is located on the server. When a user makes an initial page request, the server renders the requested page and stores the results. If the user navigates away, and then comes back to that same page, the server can immediately serve the cached content rather than re-rendering it.

    • Client-Side Cache: Enables instantaneous back-button navigation by storing route segments and data fetches on the client.
    • Server-Side Cache: Stores rendered components and fetched data on the server, allowing for faster subsequent loads.
    • Invalidation: Automatically invalidates cached data when a re-render is needed due to dynamic data changes or mutations.

    Benefits of Router Cache

    The benefits are huge. It provides faster navigation between pages, reduces the server load and provides enhanced user experience by reducing loading times.

    • Faster navigation: Cached routes load almost instantly on subsequent visits.
    • Reduced server load: Fewer server requests result in lower resource consumption.
    • Improved user experience: Seamless navigation improves overall user experience.

    Code Example

    Although the router cache operates behind the scenes, you can see how it can significantly impact performance.

            
                import { useState, useEffect } from 'react';
                
                function MyPage() {
                    const [data, setData] = useState(null);
    
                    useEffect(() => {
                        const async fetchData = async () => {
                            const res = await fetch('/api/data');
                            const data = await res.json();
                            setData(data);
                        };
                        fetchData();
                    }, []);
    
    
                    if (!data) return <div>Loading</div>;
    
                    return <div>
                        <h1>{data.title}</h1>
                        <p>{data.description}</p>
                    </div>
                }
    
                export default MyPage;
            
        

    When the above component loads, it will fetch some json data from an api route. When you navigate away from this page, the loaded component and data is stored in the cache, so when you return to it, the load time should be much lesser, resulting in an improved user experience.

    Loading UI

    Next.js 13 introduces a powerful way to handle loading states using the new loading.js file. This special file, when placed in a directory, renders UI elements during the initial load or any transition within the directory's hierarchy. This significantly improves the user experience by providing immediate visual feedback, rather than a blank page while data is being fetched.

    How it Works

    When navigating to a route, React Suspense will trigger the rendering of the loading.js file. Once the data is ready, the actual page content is rendered.

    • This is a server-side mechanism.
    • It does not require a change in your app's core logic, allowing for a non-intrusive experience for developers.
    • Each directory can have its own loading.js file, allowing for customized loading UI based on the location within the app.

    Creating a loading.js File

    To create a loading UI, create a file named loading.js or loading.tsx inside any directory within your app directory.

    Here’s an example of a simple loading component:

            
            export default function Loading() {
              return (
                <div className"flex justify-center items-center h-screen">
                    <div className"animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-stone-400"></div>
                </div>
              )
            }
            
        

    In this example, a simple spinner is shown using tailwind. You can use any valid React component as your loading UI.

    Benefits

    • Improved UX: Provides a smoother experience as users see visual feedback while data is loading, reducing the perception of latency.
    • Ease of Implementation: Simple configuration through loading.js files.
    • Customizable: Allows you to define specific loading UIs based on routes in your application.
    • Server-Side: The loading UI is server-rendered. This means that it is rendered as HTML as early as possible and is good for performance.

    Best Practices

    • Keep loading UI minimal and focused. Avoid large animations or complex layouts that may slow down the initial rendering.
    • Use subtle animations or indicators to represent the loading state.
    • Make sure your loading UI is accessible. Use appropriate ARIA attributes and provide sufficient contrast.

    Improved UX

    Improving user experience (UX) is crucial for any successful web application. It's not just about making things look pretty; it's about making them easy, intuitive, and enjoyable to use. In the context of modern web development, this often involves optimizing performance, enhancing interactivity, and ensuring a smooth user journey.

    Key Aspects of Enhanced UX

    Several elements come together to create an improved UX. Here are some of the key considerations:

    • Fast Loading Times: Users expect pages to load quickly. Slow load times can lead to frustration and abandonment. This often involves techniques like code splitting and lazy loading.
    • Intuitive Navigation: The site should be easy to navigate. Users should be able to find what they're looking for without a struggle.
    • Clear and Concise Content: Content should be easy to understand. Avoid jargon and technical terms whenever possible.
    • Responsive Design: Your app should work flawlessly on all screen sizes, from the smallest mobile devices to large desktop monitors.
    • Smooth Interactions: Elements should react quickly and fluidly to user interactions. This makes the site feel more responsive.
    • Feedback Mechanisms: Users should be clearly informed about the state of the application and whether their actions are successful. Use things like spinners and success messages.

    Techniques for Optimizing UX

    There are many techniques that can be used to improve user experience, and in modern React based frameworks like Next.js, most of them are handled under the hood. Let's look at some of them.

    • Code Splitting: Breaking your app into smaller, manageable chunks that load only when needed. This reduces the amount of code the browser needs to download on the initial page load.
    • Lazy Loading: Loading images and other resources only when they are about to appear in the user's viewport. This can drastically reduce the initial load times, especially if you have a lot of images.
    • Caching: Storing frequently accessed data in the client's cache, preventing the need to download it every time the user requests it.
    • Optimizing Images: Compressing images and using modern image formats can greatly decrease image sizes, leading to faster loading times.
    • Skeleton Loaders: Displaying a placeholder while loading content can provide a better user experience by giving the user immediate feedback and reducing perceived load times.

    Here's an example of using lazy loading with React's React.lazy and Suspense:

                
                import { lazy, Suspense } from 'react';
                
    const OtherComponent = lazy(() => import('./OtherComponent'));
    function MyComponent() {
    return (
    <div>
    <Suspense fallback={'Loading...'}>
    <OtherComponent/>
    </Suspense>
    </div>
    );
    }

    By focusing on these areas, web developers can create applications that are not only functional but also a pleasure to use. Continuously testing and gathering user feedback is essential to ensure that your application is delivering the best user experience possible.

    Join Our Newsletter

    Launching soon - be among our first 500 subscribers!

    Suggested Posts

    AI - The New Frontier for the Human Mind
    AI

    AI - The New Frontier for the Human Mind

    AI's growing presence raises critical questions about its profound effects on human psychology and cognition. 🧠
    36 min read
    8/9/2025
    Read More
    AI's Unseen Influence - Reshaping the Human Mind
    AI

    AI's Unseen Influence - Reshaping the Human Mind

    AI's unseen influence: Experts warn on mental health, cognition, and critical thinking impacts.
    26 min read
    8/9/2025
    Read More
    AI's Psychological Impact - A Growing Concern
    AI

    AI's Psychological Impact - A Growing Concern

    AI's psychological impact raises alarms: risks to mental health & critical thinking. More research needed. 🧠
    20 min read
    8/9/2025
    Read More
    Developer X

    Muhammad Areeb (Developer X)

    Quick Links

    PortfolioBlog

    Get in Touch

    [email protected]+92 312 5362908

    Crafting digital experiences through code and creativity. Building the future of web, one pixel at a time.

    © 2025 Developer X. All rights reserved.