Optimizing ReactJS applications

ReactJSWeb DevelopmentFront End Technology

In this article, we are going to see the methods to optimize our React application.

To create a real-world React application, optimized code is greatly required to enhance the performance. There are several ways to optimize a React application but some of the most preferred ways are mentioned below −

Memoization

It is the technique used to speed up the application by storing the result as the cache and only calling the function again when the inputs are changed otherwise the cached result is returned.

Use React.memo() for functional components. This method is used to only re-render the component if the props passed to component changes

Example

export default React.memp(App)

Use shouldComponentUpdate method for class based components.

Example

Class Person extends React.Component{
   shouldComponentUpdate(nextProps,nextState){
      if(nextProps.data!==this.props.data){
         return true;
      }
      return false;
   }
}

Using React.PureComponent

This method is majorly used to optimize the performance which only re-render the component if the state or props passed to the component changes.

Example

Class Person extends React.PureComponent{}

Caching Function

By using useCallbacks, we can highly optimize our React application, so that it returns only the updated result if the inputs are changed otherwise return the cached data.

Example

Const value = useCallback((a,b)=>return a+b,[a,b])

Lazy Loading

By lazily loading the not-so-necessary components of our ReactJS applications, we can highly optimize the React application as it will reduce the DOM loading time and also reduces the bundle size.

Example

Const Person = React.lazy(()=>import(‘./Person.js’))

Using Immutable Data Structures

By changing the state immutably, we can ensure to prevent temporal coupling and can also easily track the changes in the state.

state={
   user:
   {
      name: 'Rahul Bansal',
      id: '01'
   }
}

Changing state immutably

this.setState({
   user: ...this.state.user,
   {
      name: 'TutorialsPoint'
   }
})

To ensure immutability, we can also third-party dependencies like Immutable.js.

Using React.Fragments

Instead of using an extra <div> tag, we can use the <React.Fragment> to group the children tags without the need of an extra node.

Example

return (
   <React.Fragment>
      <h1>TutorialsPoint</h1>
   <React.Fragment/>
)
raja
Updated on 18-Mar-2021 11:10:34

Advertisements