Code Splitting in React

 This is an easy way to increase performance of your Front End React App. The idea is to only load your components or code when you need to. This becomes even more effective at scale, as your project becomes bigger and bigger.


1)dynamic importing - You can choose to import a file only when the app needs it. 

For example, if you have a simple app where we are importing a file name sum

import React from 'react'
import { sum } from './sum'

const Test = () => {
  return (
    <div>
        <button onClick={()=> alert(sum(2,2))}></button>
    </div>
  )
}

export default Test

We can change to it to only import when the user clicks on the button:

import React from 'react'
// import { sum } from './sum'

const Test = () => {
  return (
    <div>
        <button onClick={()=> {
          import("../sum.js").then(module => {
            module.sum
          })
          alert(sum(2,2))
        }}></button>
    </div>
  )
}

export default Test


2) dynamic importing of components - we can also apply this to React components.

We can use the lazy function instead of the normal import.

// import Logo from './Logo'
const Logo = React.lazy(() => import('./Logo'))

Then we can wrap the component in the Suspense component because we need to tell React we are loading this as needed.

import React, { Suspense } from 'react'


            <Suspense>
            <Logo />
            </Suspense>

If we are worried the component will take awhile to load(since we are loading as needed) then we can use a fallback to display a loading component

<Suspense fallback={<h1>loading...</h1>}>


Comments

Popular posts from this blog

Lifecycle of React components

Styled Components

e-commerce website built with React.nodejs