InterviewSolution
| 1. |
Explain the new feature of Lazy loading and code splitting in React v16.6? |
|
Answer» Lazy loading is the new feature introduced in React v16.6, which allows for some COMPONENTS to load later than other components. This way we can load the components which are fast like text earlier and components which LOADS images a bit later.
Now, we are lazy loading myComp as it has an image to load. Note the special way to import it and also we need to wrap the component in Suspense. Now, Suspense will contain the FALLBACK Component which will be shown while myComp gets loaded. The other component ContentComponent will load instantly. //App.js import React, { Component, lazy, Suspense } from "react"; import "./App.css"; import ContentComponent from './components/ContentComponent'; const MyComp = lazy(() => import("./components/myComp")); class App extends Component { render() { return ( <div className="App"> <header className="App-header"> <h1>Lazy Loading Demo</h1> <Suspense fallback={<div>Loading.....</div>}> <MyComp /> </Suspense> <ContentComponent /> </header> </div> ); } } export default App; //ContentComponent.js import React from 'react' export default function ContentComponent() { return ( <div> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry...</p> <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout...</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua...</p> </div> ) } //myComp.js import React from "react"; export default () => { return <img src="https://images.unsplash.com/photo-1517694712202-14dd9538aa97" width="960" height="480" alt="coding" />; };React is very fast and in localhost, condition to see it, we have to emulate Slow speed. To do so open the CONSOLE, and go to Network tab. Then click on Online and select Slow 3G. Now, when you refresh the local running app, you can see Loading…..coming. |
|