Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimize for modest hardware #18

Open
julienbrg opened this issue Jul 1, 2024 · 0 comments
Open

Optimize for modest hardware #18

julienbrg opened this issue Jul 1, 2024 · 0 comments
Assignees
Labels
enhancement New feature or request

Comments

@julienbrg
Copy link
Contributor

To ensure your application runs smoothly on devices with modest hardware, such as the Galaxy A20e, you can take several steps to optimize your Next.js app. Here’s how you can address each point:

1. Minimize Bundle Size

a. Remove Unused Dependencies

Ensure that your package.json only includes dependencies that are actually used in your project. Unnecessary dependencies can increase your bundle size.

b. Use Dynamic Imports for Code Splitting

Next.js supports dynamic imports, which allow you to split your code into smaller bundles and load them on demand.

import dynamic from 'next/dynamic'

const DynamicComponent = dynamic(() => import('../components/DynamicComponent'))

export default function Home() {
  // Use DynamicComponent where needed
}

c. Analyze Bundle Size

Use the built-in bundle analyzer to understand what’s in your bundle and optimize it.

npm install @next/bundle-analyzer

Add the following to your next.config.js:

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',
})
module.exports = withBundleAnalyzer({})

Run the build with analysis:

ANALYZE=true npm run build

d. Tree Shaking

Ensure that your project is properly tree-shaking unused code. Next.js and modern JavaScript build tools do this automatically, but it's good to be aware of.

2. Optimize Images and Assets

a. Use Next.js Image Component

Next.js provides an Image component that automatically optimizes images.

import Image from 'next/image'

export default function Home() {
  return (
    <Image
      src="/path/to/image.jpg"
      alt="Description"
      width={500}
      height={500}
    />
  )
}

b. Optimize Static Assets

Use tools like imagemin to compress images and other static assets.

3. Use Code-Splitting to Load Only Necessary Components

As mentioned earlier, use dynamic imports to split code and load components only when needed.

4. Test the App’s Performance on the Actual Device

a. Use Lighthouse

Lighthouse is a great tool for auditing your app's performance. You can run Lighthouse audits in Chrome DevTools.

  • Open your app in Chrome.
  • Open Chrome DevTools (Ctrl+Shift+I or Cmd+Option+I).
  • Go to the "Lighthouse" tab.
  • Run an audit and review the results.

b. Use Real Device Testing

Test the app directly on the Galaxy A20e:

  1. Deploy your app: Make sure your app is accessible from a public URL.
  2. Connect your device: Use USB debugging to connect your Galaxy A20e to your development machine.
  3. Open the URL in Chrome: Open the public URL in Chrome on the Galaxy A20e.
  4. Use Remote Debugging: In Chrome on your development machine, go to chrome://inspect and start a remote debugging session with your device.

c. Monitor Performance Metrics

Use performance monitoring tools like Sentry or Google Analytics to monitor how your app performs in the real world.

Example of Applying Some of These Techniques

Here's how you might update your Home component to use dynamic imports and the Image component for optimization:

import * as React from 'react'
import { Text, Button, useToast, Box } from '@chakra-ui/react'
import { useState } from 'react'
import dynamic from 'next/dynamic'
import Image from 'next/image'
import { BrowserProvider, Contract, Eip1193Provider, parseEther } from 'ethers'
import { useWeb3ModalProvider, useWeb3ModalAccount } from '@web3modal/ethers/react'

import { Head } from '../components/layout/Head'
import { SITE_NAME, SITE_DESCRIPTION } from '../utils/config'

// Dynamically import heavy components
const DynamicComponent = dynamic(() => import('../components/DynamicComponent'))

export default function Home() {
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const [data, setData] = useState<any>(null) // State to store fetched data

  const { walletProvider } = useWeb3ModalProvider()
  const provider: Eip1193Provider | undefined = walletProvider
  const toast = useToast()

  const fetchFromNestJson = async () => {
    setIsLoading(true)
    try {
      const response = await fetch('/api/fetch', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })

      if (!response.ok) {
        throw new Error(`Error: ${response.statusText}`)
      }

      const data = await response.json()
      setData(data) // Store the fetched data in the state
      console.log(data)
      toast({
        title: 'Success',
        description: 'Data fetched successfully',
        status: 'success',
        duration: 5000,
        isClosable: true,
      })
    } catch (error: any) {
      toast({
        title: 'Error',
        description: error.message,
        status: 'error',
        duration: 5000,
        isClosable: true,
      })
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <>
      <Head title={'Testing Nest.js'} description={SITE_DESCRIPTION} />
      <main>
        <Button
          colorScheme="blue"
          variant="outline"
          type="submit"
          onClick={fetchFromNestJson}
          isLoading={isLoading}
          loadingText="Fetching..."
          spinnerPlacement="end">
          Fetch
        </Button>
        {data && (
          <Box mt={4} p={4} borderWidth={1} borderRadius="md">
            <Text>ID: {data.id}</Text>
            <Text>Name: {data.name}</Text>
            <Text>Description: {data.description}</Text>
          </Box>
        )}
        <Image
          src="/path/to/image.jpg"
          alt="Description"
          width={500}
          height={500}
        />
      </main>
    </>
  )
}

By following these steps, you can optimize your Next.js application for performance, ensuring it runs efficiently even on devices with lower specifications.

@julienbrg julienbrg added the enhancement New feature or request label Jul 1, 2024
@julienbrg julienbrg self-assigned this Jul 1, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant