You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
3 Hrs
16 Min
40 Seg

Lazy Loading

16/22
Resources

How does code splitting work in React?

Code splitting is a fundamental technique for project optimization, especially in React applications. It involves separating the code into several parts, allowing only the necessary sections to be loaded when required. This significantly improves performance, especially in larger applications, by reducing the initial loading time.

What is lazy loading and how do we apply it in React?

In React, lazy loading is a technique that allows us to load components dynamically, only when they are needed. We use React.lazy for this, along with Suspense to handle the loading of these components. Next, we show how to implement lazy loading in React:

import React, { Suspense, lazy } from 'react';
// We define the component with lazy loadingconst AsyncCheckoutContainer = lazy(() => import('@containers/checkout'));
// We incorporate the component into Suspense, for handling the fallbackfunction App() { return ( <Suspense fallback={<h1>Loading...</h1>}> <AsyncCheckoutContainer/> </Suspense> );}
export default App;

With lazy loading, I reduce the initial load by deferring the unloading of the code until the user actually interacts with the specific part of the application that needs it. This is crucial for a more quickly accessible and efficient React application.

What common mistakes can we find when implementing lazy loading?

With the implementation of lazy loading, it is crucial to check for errors during its implementation. One of the common mistakes can be not importing or calling a component correctly, for example, making sure we have the correct paths in the import. An error can happen by not using Suspense properly, as it is necessary to handle loading states.

In addition, it is important to check the error console, both webpack and browser, to identify any configuration problems. A typical error is the failure to correctly open the checkout module due to incorrectly defined paths or undeclared components, leading to execution failures.

What is the importance of tuning Webpack configuration?

Webpack is key in managing how modules are packaged and loaded in our application. By configuring Webpack correctly, you improve the efficiency and organization of projects run with React.

Here is a small tweak to split chunks in the Webpack configuration:

module.exports = { // mode  mode configuration: 'development', // chunks optimization optimization: { splitChunks: { chunks: 'all', }, },}, // Rest of configuration // ...};

This setting in Webpack optimizes how code chunks are grouped and loaded, generating appropriate names for each fragment and allowing easier updates in the application without reloading all the code.

How to test our optimized React project?

Once both lazy loading and chunk splitting are configured, we need to test our application by ensuring that all resources are loaded correctly in the React application:

  1. Start Project: Run npm run start to start the React project.
  2. Check Consoles: Check both the browser console and the terminal console to identify possible loading errors.
  3. Analyze Network: Through the browser's developer tools, we can check that the resources are downloaded as expected.
  4. Functionality Check: I check that all components load and display properly, ensuring a smooth navigation without visible interruptions for the user.

In summary, by implementing lazy loading and Webpack tuning, we improve not only the performance of our application but also the user experience, which is crucial in production environments. Keep studying and experimenting with these technologies to master advanced web development techniques!

Contributions 2

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Lazy Loading

Este es una funcionalidad muy importante y funcional al momento de optimizar nuestra aplicaci贸n o p谩gina web.
Aqui esta una clase del curso de Optimizacion web que habla m谩s a profundidad acerca del Lazy Loading: Clase
Hay un Curso en Platzi de Optimizaci贸n Web que se los recomiendo mucho, ya que se puede ver como podemos, por ejemplo, ahorrar dinero optimizando nuestra web app, landing page, etc.
Link: Curso de Optimizaci贸n Web

----------- 驴Qu茅 hicimos en esta clase ? ------------
En routes > App.jsx:
Actualizamos nuestra importacion de react(la primera).

import React, { Suspense } from 'react';

Despu茅s de los imports agregamos el siguiente c贸digo:

import .....
const AsyncCheckoutContainer = React.lazy(() => {
  import("@containers/Checkout")
});

Y el template debe quedar as铆:

  return (
    <>
    {isEmpty > 0 ? (
        <Suspense fallback={<div>Loading...</div>}>
        <AppContext.Provider value={initialState}>
        <BrowserRouter>
          <Layout>
            <Switch>
              <Route exact path="/" component={Home} />
              <Route exact path="/checkout" component={AsyncCheckoutContainer} />
              <Route component={NotFound} />
            </Switch>
          </Layout>
        </BrowserRouter>
        </AppContext.Provider>
        </Suspense>
      ) : <h1>Loading ...</h1>}
    </>
  )

En webpack.config.dev.js deshabilitar hot-reload temporalmente:
Debe quedar algo as铆

module.exports = {
  entry: ['./src/index.js'], 
  .....
}

Y en devServer comentamos hot:

  devServer: {
    historyApiFallback: true,
    contentBase: path.join(__dirname, 'dist'),
    compress: true,
    port: 3005,
    // hot: true,
  },

a帽adimos despu茅s de plugins:

plugins: [
....
],
 optimization: {
   splitChunks: {
     chunks: 'all',
   },
 },

y en el output(en el comienzo de nuestro objeto):
(Cambiamos el filename)

    filename: '[name].bundle.js',

y npm run start para probar.

Mi solucion para la ultima version de react-router-dom