Why is lazy loading not the default for React? - reactjs

I am just working through a React course and the current topic is lazy loading.
I was wondering why lazy loading is not the default and taken care of by React without forcing the developer to write repetitive code?
Example:
In the course, we want to load the Posts component lazily, because in this component we only render it when on a certain route. Therefore he replaces
import Posts from './containers/posts'
with
const Posts = React.lazy(() => import('./containers/posts'))
and where it is used he replaces
<Route path='/posts' component={Posts}>
with
<Route
path='/posts'
render={() => (
<Suspense>
<Posts>
</Suspense)}
>
so basically just wrapping the component we want to lazyload in a certain React component.

React is not handling the lazy loading by itself but relies on the functionality of the underlying bundler (Webpack). In particular, the bundler converts the import() statements (which is the proposal for the dynamic import) to something which could be processed by the majority of the browsers. Thus, to enforce the underlying building process to load a specific module lazy you also have to use import().
In general, splitting into multiple chunks (that's what is happening on build when lazy loading is used) might be good (e.g. for mobile users, as mentioned by #Prashant Adhikari) but also leads to additional delays while using the page because the files have to be transferred over the network one by one first. Thus, it's also not an option to have lazy loading everywhere. In fact, this issue might disappear in the future (esp. with some "intelligent" preload mechanism in HTTP/2) but for the majority of applications the best practice over the last years seems to be generating a fat JS file for application-related scripts plus a vendor.js for the dependencies.
However, introduction of lazy loading might be reasonable in order to minimize the page loading time. Esp. for bigger applications (like Stack Overflow) it makes sense to preload the modules require to depict the primary content (e.g. Questions) and lazy load the less frequent pages (e.g. User settings).

React lazy : - It is now fully integrated into core react library itself.
Firstly, bundling involves aligning our code components in progression and putting them in one javascript chunk that it passes to the browser; but as our application grows, we notice that bundle gets very cumbersome in size. This can quickly make using your application very hard and especially slow. With Code splitting, the bundle can be split to smaller chunks where the most important chunk can be loaded first and then every other secondary one lazily loaded.
Also, while building applications we know that as a best practise consideration should be made for users using mobile internet data and others with really slow internet connections. We the developers should always be able to control the user experience even during a suspense period when resources are being loaded to the DOM.
With lazy loading you can customise and load lazily the component which are not needed for the current screen.
The question about having lazy loading natively might be answered by some more experienced guy or you can raise an issue on gitHub.

It's a relatively new feature released in the last year with React 16.6.
If there was a way to enable lazy loading for all existing projects without rewriting code, they would have included it. The fact they did not means it isn't compatible with all existing patterns.

Related

NextJS reduce First Load of shared JS

In a bigger project, I have a fairly high amount of used third-party libraries, including firebase, redux, etc and some more specific ones (but only used on several pages) like konvaJS, jimp, ....
I just migrated recently to nextJS to speed up the website & maybe allow SSR. However, after migrating, the Lighthouse Speedtest dropped compared to the Pure React Version. The main problem seems to be the shared JS first Load bundles.
After some optimizing, including lazy loading bigger Components with dynamic() & modules with await import(), I managed to compress the shared first load JS bundles by half, but they are still around 400KB which is way too heavy. I guess heavy modules like firebase are included there as well, because it is needed basically everywhere in the App.
I also tried to analyze the dependencies with #next/bundle-analyzer. But the Visualization is not really easy to interpret. Is it true that it also lists modules that are lazy loaded? And in addition, I have some dependency packed multiple times in different bundles. Last but not least, the bundles visualized by the analyzer do not match the names of the build output.
Any help to reduce or understand the process better is well appreciated. I am using current React & Next.js versions.
Edit: This is the composition of the shared JS bundles after build:
Edit2: I am still confused about the output of bundle-analyzer. The module jspdf for instance, is only used in one page / component and lazy loaded. Is it correct that it is still visible in the analyzer? It does not have any impact on the shared JS bundle size.
Edit3: I managed to lazy load my firebase modules (which are crucial for my App), so I saved over 200KB shared JS size. Still hoping to cut down the remaining. Btw, the bundle analyzers output did not really change.
Are you using FontAwesome?
We were able to reduce our "First Load JS shared by all" from
504kb down to 276kb
by removing FontAwesome dependency and downloading the individual .svg icons
directly.
Before
After

Performance gain from custom state container to Mobx?

We have a sails-js app whose ui is built with React and state container custom created with MVVM method. Our app takes ridiculously too much memory (over 400mb) even when user isn't doing anything. At times it also just crashes (on the iphone cordova build specifically). Also, even though we do not have much actions involved (except loading and playing some web audio songs etc), our webpack bundle is over 18mb (unminimised, 2,5mb minimised).
So what could be the reason for the lagging performance and the oversized bundle? How can I fix it? One option I'm thinking that will hopefully resolve the matter is to implement Mobx instead of our custom solution for state management. Because it is extremely complicated for me and there's absolutely no documentation for it. Would you have reasons that will likely resolve my problem as well?
Thanks!

What are the disadvantages of using one big React component?

What are the disadvantages of using one big React component?
I have a deep experience using webpack, browserify, AngularJS, ES6, NPM and other similar web framework. I am new to React.
I want to create a single page app in React. I don't want or need testing. I don't need team friends to work on. I only need to make the product development as fast as possible. Make thing works. You can call it MVP. You can call it type lessm, or smart developement. If things work good in the future I can consider refactoring the project. I am the only developer who works on. I don't worry about perfromance issue (if it is just few ms)
The question is: All the articles said to make as much as possible many and small React components. In separate files. You can see the React-Starter-Kit. It is huge.
You can see that every component is a separate file.There is huge webpack.config.js file. Every component import many other things. If I also want Redux, I need to import the store, and make connect on every component.
I want to take different approach. I want to use React & Redux. But using only one component. Every inner element can Dispatch or execute events.
Is there is any problems in the future that I don't think about?
HTML:
<html><head><body></body></html>
JavaScript:
App=React.createClass(function(){
getInitialState:function(){
return {
openMore:'block'
}
},
openMore:function(){
this.setState({openMore:'visible'})
},
render:function(){
return (
<div>
I want to put all the HTML of the app
<span>
In one component that do everything.
<button onClick={this.openMore}>More Info</button>
<span> This way I beleive I will need to type less for development</span>
<b style={{display:this.getState().openMore}}>What are the disadvance of this?</b>
</span>
</div>
)
}
})
ReactDOM.render(App,document.getElementsByTagName('body')[0])
Well disadvantages are many. I will try listing them from what I have faced and observed:-
React was built on the concept to break page into components, so yeah the more you break the page into small components the more it is easier to use.
Its generally easy to track the code.
Its scalable
One component does not break other components.
Re-rendering is there only for specified components if they are isolated. If you have everything in a single component, the rendering would make your entire component load again, reducing efficiency.
Harder to test
Difficult to use with redux while passing actions and then connecting to store.
Your component should do only one job.
Cannot break the components into presentational and container components thus not utilising redux to full potential.
Not being able to use code spilt feature of webpack which increase speed of page due to partial code loading.
These are few things I personally faced. Next,coming to webpack configuration. I hardly have configured webpack file more than 100 lines and trust me those 100 lines make your life really easier. In fact basic configuration is just 10-15 lines which can generate your bundle.
Now,coming to problems in future, yes following would be problems:-
Difficult to scale up.
Difficult to test
Not utilising libraries to their potential
Difficult to manage component due to monolith behavior.
Hope it helps!!!
Having a single large file is fine. React was built on the maxims "No abstraction is better than the wrong abstraction" and having an API with a low surface area.
If you're not sure what problems your application is solving, then wait until you feel the pain of not having an abstractions before you create one.
If your application is likely to be in flux as its feature set isn't nailed down, then don't give yourself busy work by moving things around in different files.
If you don't have a website that is designed with reusable components that are intuitively separable, than don't separate it out into different components.
It is fine to use React just as a means of having a declarative syntax for what your html should look like in different states.
Having large components is bad due that you cannot simplify your code. Splitting your modules into smaller ones, will make it easier for you to maintain the code at a longer term, as well as finding out an error faster. Stack Trace is easier as well as it is more composeable, when having an implicit component.
FWIW, you can do a lot more separating your component into smaller ones, such as filtered props and an own state. The bad thing though, is that you can loose track of how the application is built up when you are looking at the build others have made.

ui-router preload app (entire or partial)

The application I'm developing uses "angular.js" + "ui-router" + "bootstrap". Many states and nested views. There are also some images related to templates and, finally, animated transitions placed there to generate feeling of fluidity.
Under ideal network conditions, the application works reasonably well.
Under poor network conditions, it is bad. Sometimes animation flicks, sometimes there is a pause between the user action and the response of the interface. (for instance: the start of an animation). The feeling of flow can not be achieved.
The problems are noted when "ui-router" changes its state, the application seems to lock or flicks animations or there are sudden jumps.
The application is to be used from devices with limited bandwidth due to its geographical location.
Can I preload all or part of the application, including images and others assets?
You can concatenate and minify all JS & CSS assets (if you are not already doing so). I use grunt-neuter for dependency management. You can also bundle all the dependent libraries together (I use grunt-usemin).
I have not tried to bundle all the templates into one file, but that should also be possible. In that case, you would wrap each template within <script type="text/template"></script> blocks, have everything in DOM, and pluck out individual templates and provide to each route. This should totally eliminate flicker.
For image assets, there are grunt plugins such as grunt-spritefiles that takes a bunch of images, and create a sprite, which then can be used within your CSS.
These are some of the techniques I can think of. However, the above can significantly increase the first time load. It may be acceptable for the use case you are describing. Hope this helps!

Feasibility of using angular js for web app with over 200 medium to complex screens

My team was considering using angular js for web app UI development. But knowing at a high level how single page apps work, I had a question as to, how feasible it is to use angular js framework, for a large web application. this would have at least 200 screens, each screen containing an average of 30 UI controls like text boxes, calendar controls, drop downs etc.
The user will be accessing the web app on desktop or laptop and will be using the application in the browser throughout an 8 hour day, without ever closing the browser.
Given above usage, would angular js, memory usage / performance be issue?
are there web apps with huge and complex UI, built using angular js, that are in production and used everyday?
You can have not just 200 but 1000's of screens - this number does not matter as long as you address the core and fundamental questions below. They all boil down to memory and performance.
At a given point of time how many $watches will be active.
At a given point of time how many listeners are created.
At a given point of time what is the complexity of DOM i.e. the number of DOM elements and thee nesting/depth.
At a given point of time how many Javascript modules (services, controllers etc.) will be loaded in the memory. Even though these things are singletons they consume memory.
For each such screen how much memory will be consumed (if you use jqueryUI etc. your memory increases quite rapidly than pure angular + html components)
This brings to what you can do to control the above factors which if not watched will make your application sink/crash.
1) How do you break the run-time complexities of your "big" application ? You can now think of "Routers" or dialogs. Each of your screen will come-and-go i.e. you will never display 200 screens the same time.
2) Make sure when the screen is gone there is no "leftover". Don't use jQuery - if you do make sure you clean this on $scope.$destroy.
3) Multitudes of directives:- Directives are powerful but don't over use it - try not to deep nest too many of them. templateUrl is "tempting" but sometimes in-lining a template is the best choice. Use build tools that will inline the templates.
4) Load modules on demand using requireJS. This will force you to modularize your application and think hard about concatention strategy (combining JS files). Will force you to write independent modules.
5) Browser caching your assets and a good cache busting mechanism. Grunt based plugins are to your rescue. Minify your assets.
6) Compresss the assets for efficient network utilization and faster transmission.
7) Keep your app encapsulated in Angular. Don't create any global objects. Chances are that they have access to some closure or are referring to some things within angular $scope and $scopes are now still hanging on or are in difficult trajectory to be able to get Garbage Collected.
8) Use one-time-bind or bind-once model binding as much as possible.
9) Splash screen is an excellent weapon - us it. Helps you load some stuff upfront while the user watches smooth/jazzy picture/picture :)
Regarding 8 hours a day constant use
Unless there is a leak of the following kind you should be fine:-
1) Listeners leaking i.e. hanging around.
2) DOM leaks. Detached DOM issue.
3) Size of Javascript objects. Javascript objects coded in a certain way creates repeated instances of function.
(I am developing AngularJS app - with more than 450 screen - MDI like app. The app is not yet in production. The above points are coming from my burnouts in the functionality we have developed so far.)
I've worked on multiple projects that are extremely large single-page applications in Angular and Ember.JS at companies like McKesson an Netflix.
I can tell you for a fact that it's completely "feasible" to build "huge, complex" applications with frameworks such as Angular. In fact, I believe Angular is uniquely well suited to this because of it's modular structure.
One thing to consider when creating your Angular application is whether or not every user will benefit from all "200 pages" of your application. That is to say, is it necessary to have all 200 views be part of the same single page application? Or should you break it into a few single page applications with views that share concerns.
A few tips:
Watch out for name collisions in the IOC container: If you create enough services and controllers, even if you break them into separate modules, it's very easy to create two services with the same name. This may or may not result in an outright error. What happens when you register two "fooService" services? The last one wins.
If you decide to break your app into more than one single page app, you have to be sure you have solid boundaries of functionality between the two. They're not going to be able to share state easily other than with something like cookies or local storage.
If you decide to keep everything in one single page app, you're going to want to keenly watch your initial download time. Always check to see how long it takes to start your app "cold" over a slow-ish connection. If the entire app is in one bundle, depending on how you structure things (are you going to use AMD?) then you might see a long initial load time.
AVOID rendering HTML on your server. I can't stress this enough. Let Angular do that work for you. The only rendering your server should be doing is rendering JSON to be returned from some RESTful service.
Flush out your JS build process early on. Look into Node-based tools like Grunt, Gulp, and Broccoli for linting/concatenating/minifying your JS files. Checkout Karma for running unit tests, and look into Istanbul for code coverage. Protractor is a great tool as well, but I recommend strong unit tests in Karma over integration tests with Protractor just because Web Driver based tests tend to be brittle.
Other than that, I think you'll find a single page app written in any modern framework to be extremely snappy after the initial load is done. In fact, it will make any "old" PHP/ASP.Net style app that renders the entire page at the server seem slow as dirt in comparison. This is because you'll only be loading data and the occasional .html file over HTTP.

Resources