My experience on my daily works... helping others ease each other

Thursday, December 19, 2019

Improving and Managing the Applications Performance

I was developing my personal resume mobile apps using Ionic Framework + React and Capacitor. It is using a few JSON files so that I can easily manage it in the future.

It works perfectly when I run npm start or ionic serve command. However, when I move it to mobile apps, there start a problem. It is lagging despite running on an emulator or even on my devices and I'm just using local files.

After days of googling and try-n-error, I found a good solution to it. Used

  • Lazy
  • Suspend
  • Error controller


And it should solve it.

Here it is done:

1. Lazy & Suspend

import React, {lazy, Suspense, Component} from 'react';
//import { IonContent, IonHeader, IonItem, IonLabel, IonList, IonPage, IonTitle, IonToolbar } from '@ionic/react';

const AboutPage = lazy(() => import('./AboutPage'));

class Abouts extends Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
details: true
}
}
showDetails() {
this.setState({ details: true });
}
renderLoader = () => <div className="loader">Loading About & Credit...</div>;
render() {
const { details } = this.state;
return (
<div className="divLoading">
{ details &&
<Suspense fallback={this.renderLoader()}>
<AboutPage />
</Suspense>
}
</div>
);
}
}
export default Abouts;

2. Error controller

class ErrorBoundary extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = {hasError: false};
}

static getDerivedStateFromError(error: any) {
return {hasError: true};
}

render() {
if (this.state.hasError) {
return <p>Loading failed! Please reload.</p>;
}

return this.props.children;
}
}
.....
#part of your code
<ErrorBoundary>
<Suspense fallback={this.renderLoader()}>
<ThePageToLoad />
</Suspense>
</ErrorBoundary>

All is based on the following resources. Credit goes to them who help me to solve it:

  1. https://web.dev/code-splitting-suspense/
  2. https://codesandbox.io/s/7zx3jlrry1?from-embed
  3. https://www.freecodecamp.org/news/how-to-optimize-react-applications-with-lazy-loading-232183e02768/
Share:

0 comments:

About Me

Somewhere, Selangor, Malaysia
An IT by profession, a beginner in photography

Blog Archive

Blogger templates