Learn Next.js: A Beginner’s Guide

Okay, here’s a long-form article (approximately 5000 words) diving deep into “Learn Next.js: A Beginner’s Guide,” covering various aspects of the framework and providing a comprehensive overview for someone starting their journey with Next.js.

Learn Next.js: A Beginner’s Guide – A Comprehensive Introduction

Next.js has rapidly become one of the most popular and powerful frameworks for building modern web applications. Built on top of React, it provides a structured and opinionated approach to development, enabling developers to create performant, SEO-friendly, and scalable websites and applications with ease. This guide aims to be your comprehensive starting point, walking you through the fundamental concepts, core features, and practical applications of Next.js, even if you’re relatively new to React or web development in general.

Table of Contents:

  1. Why Next.js? The Advantages and Use Cases

    • The Problems with Traditional Client-Side Rendering (CSR)
    • Server-Side Rendering (SSR) Explained
    • Static Site Generation (SSG) Explained
    • Incremental Static Regeneration (ISR) Explained
    • Client-Side Rendering (CSR) in Next.js
    • Performance Benefits
    • SEO Benefits
    • Developer Experience (DX)
    • Built-in Features and Optimizations
    • Large and Active Community
    • Use Cases: When to Choose Next.js
  2. Prerequisites and Setting Up Your Development Environment

    • Basic Understanding of HTML, CSS, and JavaScript
    • Familiarity with React Fundamentals (Components, Props, State, JSX)
    • Node.js and npm (or yarn) Installation
    • Choosing a Code Editor (VS Code, Sublime Text, etc.)
    • Creating Your First Next.js Project (create-next-app)
    • Understanding the Project Structure
    • Running the Development Server
  3. Core Concepts: Pages, Routing, and Navigation

    • The pages Directory: The Heart of Routing
    • File-Based Routing: How it Works
    • Creating Basic Pages (index.js, about.js, etc.)
    • Dynamic Routes ([id].js, [slug].js)
    • Catch-all Routes ([...slug].js)
    • Nested Routes
    • The <Link> Component for Client-Side Navigation
    • Programmatic Navigation with useRouter
    • Linking to External Pages
  4. Data Fetching: Getting Data into Your Components

    • getStaticProps (for Static Site Generation – SSG)
      • Fetching Data at Build Time
      • Passing Data as Props
      • Using getStaticPaths with Dynamic Routes
      • Understanding Revalidation (ISR)
    • getServerSideProps (for Server-Side Rendering – SSR)
      • Fetching Data on Each Request
      • Accessing Request Data (e.g., Cookies, Headers)
    • Client-Side Data Fetching with useEffect
      • Using fetch or axios
      • Handling Loading and Error States
    • Choosing the Right Data Fetching Method
  5. Styling Your Next.js Application

    • Global Styles (using _app.js)
    • Component-Level Styles (CSS Modules)
    • Styled-JSX (Inline Styles)
    • CSS-in-JS Libraries (Styled Components, Emotion)
    • Integrating CSS Frameworks (Tailwind CSS, Bootstrap)
  6. Built-in Components and APIs

    • <Head>: Managing Document Head Elements (Title, Meta Tags)
    • <Image>: Optimized Image Loading and Performance
    • <Script>: Managing Third-Party Scripts
    • API Routes: Building Serverless Functions
      • Creating API Endpoints
      • Handling Requests and Responses
      • Connecting to Databases or External APIs
    • Environment Variables
  7. Deployment: Getting Your App Online

    • Vercel: The Recommended Platform
      • Zero-Configuration Deployment
      • Automatic Scaling and CDN
      • Preview Deployments
    • Netlify
    • Other Hosting Options (AWS, Google Cloud, etc.)
    • Static Export (next export)
  8. Advanced Topics (Brief Overview)

    • Authentication (NextAuth.js)
    • Internationalization (i18n)
    • Testing (Jest, React Testing Library)
    • TypeScript Integration
    • Custom Server
    • Customizing Webpack Configuration
    • Middleware
  9. Best Practices and Common Patterns

    • Code Splitting
    • Prefetching
    • Error Handling
    • Accessibility (a11y)
    • Performance Optimization
  10. Resources and Further Learning

    • Official Next.js Documentation
    • Next.js Learn Course
    • Community Forums and Discord
    • Blogs, Tutorials, and Videos

1. Why Next.js? The Advantages and Use Cases

Before diving into the technical details, it’s crucial to understand why Next.js has gained so much popularity. What problems does it solve, and what benefits does it offer over traditional approaches to web development?

  • The Problems with Traditional Client-Side Rendering (CSR):

    In a purely client-side rendered (CSR) application (like a basic React app without a framework like Next.js), the browser initially receives a nearly empty HTML file with a JavaScript bundle. The JavaScript then executes, fetches data, and renders the content dynamically. This leads to a few key problems:

    • Poor Initial Load Performance: Users might see a blank screen or a loading spinner for a significant amount of time while the JavaScript downloads and executes. This is especially problematic on slower networks or devices.
    • SEO Challenges: Search engine crawlers often have difficulty indexing content that’s rendered dynamically by JavaScript. Since the initial HTML is empty, the crawler might not see the actual content, leading to poor search engine rankings.
    • Initial blank page: This happens until javascript is downloaded, parsed and executed.
  • Server-Side Rendering (SSR) Explained:

    Server-side rendering (SSR) addresses these issues by rendering the initial HTML on the server. When a user requests a page, the server fetches the necessary data, generates the complete HTML, and sends it to the browser. This results in:

    • Faster Initial Load: The user sees the content immediately, improving perceived performance and user experience.
    • Improved SEO: Search engine crawlers receive the fully rendered HTML, making it easier to index the content.
    • Better First Contentful Paint (FCP) and Largest Contentful Paint (LCP): These are key web performance metrics that are significantly improved with SSR.
  • Static Site Generation (SSG) Explained:

    Static Site Generation (SSG) takes the concept of pre-rendering a step further. Instead of rendering the HTML on each request (like SSR), SSG generates the HTML files at build time. These static HTML files are then served directly from a CDN (Content Delivery Network), resulting in incredibly fast loading times.

    • Blazing Fast Performance: Serving static files is inherently faster than running server-side code.
    • Reduced Server Load: Since there’s no server-side processing on each request, the server load is significantly reduced.
    • Enhanced Security: Static sites are less vulnerable to certain types of attacks since there’s no dynamic server-side code execution.
    • Ideal for Content-Heavy Sites: SSG is perfect for blogs, documentation sites, marketing pages, and other content that doesn’t change frequently.
  • Incremental Static Regeneration (ISR) Explained:

    Incremental Static Regeneration (ISR) is a powerful feature of Next.js that combines the benefits of SSG and SSR. It allows you to generate static pages at build time and update them in the background at a specified interval. This means you get the speed of SSG with the ability to keep your content fresh.

    • Static Speed with Dynamic Updates: You get the initial performance benefits of SSG, but your content can be updated without requiring a full rebuild of the entire site.
    • Stale-While-Revalidate: Next.js serves the stale (cached) version of the page while it regenerates the page in the background. The next request will then receive the updated version.
    • Perfect for Content that Changes Regularly: Ideal for e-commerce product pages, news articles, and other content that needs to be updated frequently but not on every single request.
  • Client-Side Rendering (CSR) in Next.js:

    Next.js doesn’t force you to choose only SSR or SSG. You can still use client-side rendering (CSR) for parts of your application that require highly dynamic updates or user-specific data. This flexibility is a key advantage of Next.js.

  • Performance Benefits:

    The combination of SSR, SSG, ISR, and optimized image handling (with the <Image> component) leads to significant performance improvements. Faster loading times translate to a better user experience, lower bounce rates, and improved conversion rates.

  • SEO Benefits:

    The pre-rendered HTML generated by SSR and SSG makes your site much more easily crawlable by search engines, leading to better search engine rankings and increased organic traffic.

  • Developer Experience (DX):

    Next.js provides a fantastic developer experience with features like:

    • Fast Refresh: Changes to your code are reflected almost instantly in the browser without losing component state.
    • Built-in Routing: File-based routing makes it incredibly easy to create and manage pages.
    • Zero Configuration: Next.js handles a lot of the complex configuration (Webpack, Babel) behind the scenes, allowing you to focus on building your application.
    • API Routes: Easily create serverless functions to handle backend logic.
  • Built-in Features and Optimizations:

    Next.js comes with a wealth of built-in features and optimizations, including:

    • Image Optimization: The <Image> component automatically optimizes images for different screen sizes and formats (WebP).
    • Code Splitting: Next.js automatically splits your code into smaller chunks, loading only the necessary JavaScript for each page.
    • Prefetching: Next.js prefetches the resources for linked pages in the background, making navigation even faster.
    • Font Optimization: Automatic font optimization to reduce layout shift.
  • Large and Active Community:

    Next.js has a large and active community, which means you’ll find plenty of resources, tutorials, and support online.

  • Use Cases: When to Choose Next.js:

    Next.js is a versatile framework that can be used for a wide range of projects, including:

    • Blogs and Documentation Sites: SSG is perfect for these types of content-heavy sites.
    • E-commerce Websites: SSR and ISR can be used to create fast and dynamic product pages.
    • Marketing Landing Pages: SSG ensures fast loading times and improved conversion rates.
    • Dashboards and Web Applications: SSR and CSR can be combined to build complex and interactive applications.
    • Hybrid Applications: Mix and match SSR, SSG, and CSR to create the optimal solution for your specific needs.

2. Prerequisites and Setting Up Your Development Environment

Before you can start building with Next.js, you’ll need to have a few things in place:

  • Basic Understanding of HTML, CSS, and JavaScript:

    Next.js builds on top of these fundamental web technologies, so a solid understanding of them is essential. You should be comfortable with:

    • HTML: Structuring content with elements like headings, paragraphs, lists, images, and links.
    • CSS: Styling HTML elements, using selectors, properties, and values.
    • JavaScript: Adding interactivity to web pages, working with variables, functions, objects, and the DOM (Document Object Model).
  • Familiarity with React Fundamentals (Components, Props, State, JSX):

    Next.js is a React framework, so you’ll need to have a basic understanding of React concepts:

    • Components: Reusable building blocks of UI.
    • Props: Data passed from parent components to child components.
    • State: Data that changes within a component over time.
    • JSX: A syntax extension to JavaScript that allows you to write HTML-like code within your JavaScript files.
    • Hooks: Functions that let you “hook into” React state and lifecycle features from function components (useState, useEffect, etc.).
  • Node.js and npm (or yarn) Installation:

    Next.js requires Node.js (a JavaScript runtime) and npm (Node Package Manager) or yarn (an alternative package manager) to be installed on your system.

    • Download and Install Node.js: Go to the official Node.js website (https://nodejs.org/) and download the LTS (Long-Term Support) version for your operating system. The installer will also install npm.
    • Verify Installation: Open your terminal or command prompt and run the following commands to verify that Node.js and npm are installed correctly:
      bash
      node -v
      npm -v

      These commands should display the installed versions of Node.js and npm.

    • (Optional) Install Yarn: If you prefer to use yarn instead of npm, you can install it globally using npm:
      bash
      npm install -g yarn

      Then, verify the installation:
      bash
      yarn -v

  • Choosing a Code Editor (VS Code, Sublime Text, etc.):

    You’ll need a code editor to write and edit your Next.js code. Some popular options include:

    • Visual Studio Code (VS Code): A free, open-source, and highly extensible code editor with excellent support for JavaScript and React development. (Highly recommended)
    • Sublime Text: A lightweight and fast code editor.
    • Atom: Another popular open-source code editor.
    • WebStorm: A powerful (but paid) IDE from JetBrains.

    Install your preferred code editor and configure it with any extensions or themes you like. For VS Code, consider installing the “ES7+ React/Redux/React-Native snippets” and “Prettier – Code formatter” extensions.

  • Creating Your First Next.js Project (create-next-app):

    The easiest way to create a new Next.js project is to use create-next-app, a command-line tool that sets up everything for you.

    1. Open your terminal or command prompt.
    2. Navigate to the directory where you want to create your project.
    3. Run the following command:

      bash
      npx create-next-app my-next-app

      Replace my-next-app with the desired name for your project. You can also use yarn:

      bash
      yarn create next-app my-next-app

      4. Wait for the installation to complete. create-next-app will download the necessary dependencies and create the project structure.
      5. Change directoy into the project.
      cd my-next-app

  • Understanding the Project Structure:

    After the installation is complete, you’ll have a new directory with the name you chose for your project. Here’s a breakdown of the key files and directories:

    • pages/: This is the most important directory. It contains your application’s pages, and the file structure within this directory determines your website’s routing.
      • index.js: The home page of your application (e.g., yourdomain.com/).
      • _app.js: A special file used to initialize pages. You can use it to add global styles, persist layout between page changes, and more.
      • api/: This directory contains your API routes (serverless functions).
    • public/: This directory contains static assets like images, fonts, and other files that should be served directly.
    • styles/: This directory is a common place to store your CSS files (although you can organize your styles differently).
      • globals.css: Where global styles are applied.
      • Home.module.css: Example of a CSS Module file.
    • components/ A suggested directory to hold your React components.
    • package.json: This file contains metadata about your project, including its dependencies and scripts.
    • next.config.js: An optional file that allows you to customize Next.js’s configuration.
    • .gitignore: Specifies intentionally untracked files that Git should ignore.
    • README.md: A markdown file to describe your project.
  • Running the Development Server:

    To start the Next.js development server, run one of the following commands in your project’s root directory:

    bash
    npm run dev # Using npm

    or

    bash
    yarn dev # Using yarn

    This will start the development server, typically on http://localhost:3000. Open your web browser and navigate to this address, and you should see the default Next.js starter page. The development server has built-in hot reloading, so any changes you make to your code will be automatically reflected in the browser.

3. Core Concepts: Pages, Routing, and Navigation

Routing is a fundamental aspect of any web application. It determines how users navigate between different pages and sections of your site. Next.js provides a powerful and intuitive file-based routing system that makes it incredibly easy to manage your application’s routes.

  • The pages Directory: The Heart of Routing

    The pages directory is the core of Next.js’s routing system. Every .js, .jsx, .ts, or .tsx file within the pages directory automatically becomes a route based on its filename.

  • File-Based Routing: How it Works

    The file-based routing system works as follows:

    • pages/index.js: Corresponds to the root route (/).
    • pages/about.js: Corresponds to the /about route.
    • pages/blog.js: Corresponds to the /blog route.
    • pages/products/index.js: Corresponds to the /products route.
    • pages/products/shoes.js: Corresponds to the /products/shoes route.

    The file structure directly maps to the URL structure. This makes it very easy to understand and manage your application’s routes.

  • Creating Basic Pages (index.js, about.js, etc.)
    Let’s create a simple example. Inside your pages directory, you should already have an index.js file. This is your homepage. Let us create an about.js page:

    1. Create a new file named about.js inside the pages directory.

    2. Add the following code to about.js:

      “`javascript
      // pages/about.js
      function AboutPage() {
      return (

      About Us

      This is the about page of our website.

      );
      }

      export default AboutPage;
      “`

    3. Save the file.

    4. Open your browser and navigate to http://localhost:3000/about. You should see the content of your AboutPage component.

    You can create as many pages as you need, simply by adding new files to the pages directory.

  • Dynamic Routes ([id].js, [slug].js)

    Often, you’ll need to create routes that include dynamic segments, such as a product ID or a blog post slug. Next.js allows you to create dynamic routes using square brackets ([]) in the filename.

    • Example: pages/products/[id].js

      This file will handle routes like /products/1, /products/2, /products/abc, etc. The value within the brackets (id in this case) becomes a query parameter that you can access within your component.

      “`javascript
      // pages/products/[id].js
      import { useRouter } from ‘next/router’;

      function ProductPage() {
      const router = useRouter();
      const { id } = router.query;

      return (

      Product Details

      Product ID: {id}

      );
      }

      export default ProductPage;
      “`

      In this example, the useRouter hook from next/router is used to access the router object. The query property of the router object contains the dynamic segments of the URL. So, if you navigate to /products/123, the id variable will be equal to "123".

    • Example: pages/blog/[slug].js

      This is commonly used for blog posts, where the slug is a URL-friendly version of the post title.

      “`javascript
      // pages/blog/[slug].js
      import { useRouter } from ‘next/router’;

      function BlogPostPage() {
      const router = useRouter();
      const { slug } = router.query;

      return (

      Blog Post

      Slug: {slug}

      );
      }

      export default BlogPostPage;
      “`

  • Catch-all Routes ([...slug].js)
    Catch-all routes allow you to match any number of path segments. They use three dots (...) inside the square brackets.

    • Example: pages/docs/[...slug].js

    This file will handle routes like /docs/getting-started, /docs/api/reference, /docs/a/b/c, etc. The slug will be an array of path segments.

    ```javascript
    // pages/docs/[...slug].js
    import { useRouter } from 'next/router';
    
    function DocsPage() {
      const router = useRouter();
      const { slug } = router.query;
    
      return (
        <div>
          <h1>Documentation</h1>
          <p>Slug: {slug ? slug.join('/') : 'Home'}</p> {/* Join the array elements */}
        </div>
      );
    }
    
    export default DocsPage;
    ```
    
    If you visit `/docs/api/reference`, `slug` will be `['api', 'reference']`.  If you visit `/docs`, `slug` will be `undefined`.
    
  • Nested Routes

    You can create nested routes by creating nested directories within the pages directory. For example:

    • pages/products/index.js -> /products
    • pages/products/shoes.js -> /products/shoes
    • pages/products/[id].js -> /products/:id
    • pages/blog/index.js -> /blog
    • pages/blog/[slug].js -> /blog/:slug

    This allows you to create a well-organized and hierarchical routing structure.

  • The <Link> Component for Client-Side Navigation

    While you can use regular <a> tags for navigation, Next.js provides a <Link> component that offers significant advantages for client-side navigation:

    • Client-Side Transitions: <Link> uses client-side routing, which means that page transitions happen without a full page reload. This results in a much smoother and faster user experience.
    • Prefetching: <Link> automatically prefetches the resources for the linked page in the background (when the link is visible in the viewport), making navigation even faster.

    To use the <Link> component, you need to import it from next/link:

    “`javascript
    // pages/index.js
    import Link from ‘next/link’;

    function HomePage() {
    return (

    Welcome to My Website


    About Us

    );
    }

    export default HomePage;
    “`

    • href prop: Specifies the URL of the page to link to. This should be the path relative to the pages directory (e.g., /about, /products/123).
    • <a> tag: The Link component must wrap an <a> tag. The <a> tag provides accessibility benefits and allows users to open the link in a new tab or window.
  • Programmatic Navigation with useRouter

    Sometimes, you might need to navigate programmatically, such as after a form submission or in response to a user action. You can use the useRouter hook from next/router to achieve this:

    “`javascript
    // pages/contact.js
    import { useRouter } from ‘next/router’;

    function ContactPage() {
    const router = useRouter();

    const handleSubmit = async (event) => {
    event.preventDefault();
    // … submit the form data …

    // Redirect to the thank you page after successful submission
    router.push('/thank-you');
    

    };

    return (

    Contact Us

    {/ … form fields … /}

    );
    }

    export default ContactPage;
    “`

    • router.push(href): Navigates to the specified URL.
    • router.replace(href): Navigates to the specified URL, replacing the current history entry (the user won’t be able to go back to the previous page using the browser’s back button).
    • router.back(): Navigates back to the previous page.
    • router.reload(): Reloads the current page.
    • router.prefetch(href): Prefetches the specified URL.
  • Linking to External Pages

    For links to external websites, you should use regular <a> tags without the <Link> component:

    javascript
    function HomePage() {
    return (
    <div>
    <h1>Welcome</h1>
    <a href="https://www.example.com" target="_blank" rel="noopener noreferrer">
    Visit Example Website
    </a>
    </div>
    );
    }
    export default HomePage;

    • target="_blank": Opens the link in a new tab or window.
    • rel="noopener noreferrer": Improves security and prevents the linked page from accessing the window.opener object. This is a recommended best practice for external links.

4. Data Fetching: Getting Data into Your Components

Data fetching is a crucial part of building dynamic web applications. Next.js provides several methods for fetching data, each with its own advantages and use cases. Understanding these methods is key to building performant and scalable Next.js applications.

  • getStaticProps (for Static Site Generation – SSG)

    getStaticProps is used to fetch data at build time. This is ideal for data that doesn’t change frequently, such as blog posts, product descriptions, or marketing content. The data is fetched when you build your application (e.g., when you run npm run build), and the resulting HTML is generated as static files.

    • Fetching Data at Build Time:

      “`javascript
      // pages/blog.js
      function BlogPage({ posts }) {
      return (

      Blog

        {posts.map((post) => (

      • {post.title}

        {post.excerpt}

      • ))}

      );
      }

      export async function getStaticProps() {
      // Fetch data from an API or database
      const res = await fetch(‘https://your-api.com/posts’);
      const posts = await res.json();

      // Return the data as props
      return {
      props: {
      posts,
      },
      };
      }

      export default BlogPage;
      “`

      • getStaticProps is an async function that runs on the server-side at build time.
      • It can fetch data from any source, such as an API, a database, or the file system.
      • It must return an object with a props property. The props property will be passed to the page component as props.
    • Passing Data as Props:

      The data returned by getStaticProps is passed to your page component as props. You can then use this data to render your component.

    • Using getStaticPaths with Dynamic Routes:

      When you use dynamic routes (e.g., pages/blog/[slug].js), you need to tell Next.js which paths to generate at build time. This is where getStaticPaths comes in.

      “`javascript
      // pages/blog/[slug].js
      function BlogPostPage({ post }) {
      return (

      {post.title}

      {post.content}

      );
      }

      export async function getStaticPaths() {
      // Fetch a list of all post slugs
      const res = await fetch(‘https://your-api.com/posts’);
      const posts = await res.json();

      // Generate an array of paths with the slug parameter
      const paths = posts.map((post) => ({
      params: { slug: post.slug },
      }));

      // Return the paths
      return {
      paths,
      fallback: false, // See below for fallback options
      };
      }

      export async function getStaticProps({ params }) {
      // Fetch the data for a single post based on the slug
      const res = await fetch(https://your-api.com/posts/${params.slug});
      const post = await res.json();

      return {
      props: {
      post,
      },
      };
      }

      export default BlogPostPage;
      “`

      • getStaticPaths is also an async function that runs at build time.
      • It must return an object with a paths property.
      • The paths property should be an array of objects, where each object has a params property. The params property should match the dynamic segments in your filename (e.g., { slug: 'my-post-slug' }).
      • The fallback property controls what happens if a user requests a path that wasn’t generated at build time:
        • fallback: false: Returns a 404 page.
        • fallback: true: Next.js will attempt to generate the page on the first request and then cache it for future requests. This shows a loading state, then renders the page.
        • fallback: 'blocking': Similar to true, but it will server-side render the page on the first request without showing a loading state.
    • Understanding Revalidation (ISR):

      getStaticProps also supports Incremental Static Regeneration (ISR), which allows you to update your static pages in the background after the initial build. You can specify a revalidate option (in seconds) to tell Next.js how often to regenerate the page.

      “`javascript
      export async function getStaticProps() {
      // … fetch data …

      return {
      props: {
      // … your data …
      },
      revalidate: 60, // Regenerate the page at most once every 60 seconds
      };
      }
      “`

      With ISR, Next.js uses a “stale-while-revalidate” strategy:

      1. The first request after the revalidate time has elapsed will still serve the stale (cached) version of the page.
      2. Next.js regenerates the page in the background.
      3. Once the page is regenerated, subsequent requests will receive the updated version.

      This ensures that users always see a fast response, even if the data is being updated.

  • getServerSideProps (for Server-Side Rendering – SSR)

    getServerSideProps is used to fetch data on each request. This is ideal for data that changes frequently or is specific to the user, such as user authentication data, shopping cart contents, or personalized recommendations.

    • Fetching Data on Each Request:

      “`javascript
      // pages/profile.js
      function ProfilePage({ user }) {
      return (

      User Profile

      Name: {user.name}

      Email: {user.email}

      );
      }

      export async function getServerSideProps(context) {
      // Fetch user data from an API or database
      const res = await fetch(https://your-api.com/users/${context.req.cookies.userId});
      const user = await res.json();

      return {
      props: {
      user,
      },
      };
      }

      export default ProfilePage;
      “`

      • getServerSideProps is an async function that runs on the server-side on every request.
      • It receives a context object as an argument, which contains information about the request, including:
        • context.req: The Node.js HTTP request object.
        • context.res: The Node.js HTTP response object.
        • context.params: The route parameters (for dynamic routes).
        • context.query: The query string parameters.
        • context.resolvedUrl: The resolved URL for the request.
        • context.locale: The current locale (for internationalization).
      • Like getStaticProps, it must return an object with a props property.
    • Accessing Request Data (e.g., Cookies, Headers):

      You can access request-specific data, such as cookies and headers, from the context.req object. This allows you to fetch data based on the user’s session or other request-specific information.

  • Client-Side Data Fetching with useEffect

    For data that needs to be fetched after the initial render, or in response to user interactions, you can use client-side data fetching with the useEffect hook.

    • Using fetch or axios:
      “`javascript
      import { useState, useEffect } from ‘react’;

    function MyComponent() {
    const [data, setData] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        async function
    

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top