Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Optimizing performance #191

Closed
wants to merge 11 commits into from
110 changes: 54 additions & 56 deletions content/docs/optimizing-performance.md
@@ -1,93 +1,91 @@
---
id: optimizing-performance
title: Optimizing Performance
title: Optimizando el Rendimiento
permalink: docs/optimizing-performance.html
redirect_from:
- "docs/advanced-performance.html"
---

Internally, React uses several clever techniques to minimize the number of costly DOM operations required to update the UI. For many applications, using React will lead to a fast user interface without doing much work to specifically optimize for performance. Nevertheless, there are several ways you can speed up your React application.
Internamente, React utiliza diferentes técnicas inteligentes para minimizar el número de operaciones DOM costosas requeridas para actualizar la interfaz de usuario. Para muchas aplicaciones, el uso de React conllevará a una interfaz de usuario rápida sin hacer mucho trabajo para optimizar específicamente el rendimiento. Sin embargo, hay varias maneras de acelerar tu aplicación de React.

## Use the Production Build {#use-the-production-build}
## Usar la *Build* de Producción

If you're benchmarking or experiencing performance problems in your React apps, make sure you're testing with the minified production build.
Si estás haciendo análisis comparativos o experimentando problemas de rendimiento en tus aplicacions de React, asegúrate que estas probando con una *build* minificada.

By default, React includes many helpful warnings. These warnings are very useful in development. However, they make React larger and slower so you should make sure to use the production version when you deploy the app.
Por defecto, React incluye muchas alertas útiles. Estas alertas son muy útiles en desarrollo. Sin embargo, estas hacen a React más pesado y lento, así que debes asegurarte de usar la versión de producción cuando desplieges la aplicación.

If you aren't sure whether your build process is set up correctly, you can check it by installing [React Developer Tools for Chrome](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi). If you visit a site with React in production mode, the icon will have a dark background:
Si no estás seguro si tu proceso de *build* está configurado correctamente, puedes revisarlo instalando [React Developer Tools for Chrome](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi). Si visitas un sitio con React en modo de producción, el ícono tendrá un fondo oscuro:

<img src="../images/docs/devtools-prod.png" style="max-width:100%" alt="React DevTools on a website with production version of React">

If you visit a site with React in development mode, the icon will have a red background:
Si visitas un sitio con React en modo de desarrollo, el ícono tendrá un fondo rojo:

<img src="../images/docs/devtools-dev.png" style="max-width:100%" alt="React DevTools on a website with development version of React">

It is expected that you use the development mode when working on your app, and the production mode when deploying your app to the users.
Se espera que uses el modo de desarrollo cuando estás trabajando en tu aplicación, y el modo de producción cuando despliegues tu aplicación a los usuarios.

You can find instructions for building your app for production below.
Abajo puedes encontrar las instrucciones para construir tu aplicación de producción.

### Create React App {#create-react-app}

If your project is built with [Create React App](https://github.com/facebookincubator/create-react-app), run:
Si tu proyecto fui construido con [Create React App](https://github.com/facebookincubator/create-react-app), ejecuta:

```
npm run build
```

This will create a production build of your app in the `build/` folder of your project.
Esto creará una *build* de producción de tu aplicación el directorio `build/` de tu proyecto.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Esto creará una *build* de producción de tu aplicación el directorio `build/` de tu proyecto.
Esto creará una *build* de producción de tu aplicación en el directorio `build/` de tu proyecto.


Remember that this is only necessary before deploying to production. For normal development, use `npm start`.
Recuerda que esto es solo una necesidad antes de desplegar a producción. Para el desarrollo normal, usa `npm start`.

### Single-File Builds {#single-file-builds}

We offer production-ready versions of React and React DOM as single files:
Ofrecemos versiones listas para producción de React y React DOM como un archivo:

```html
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
```

Remember that only React files ending with `.production.min.js` are suitable for production.
Recuerda que solo los archivos de React que terminan con `production.min.js` son apropiados para producción.

### Brunch {#brunch}

For the most efficient Brunch production build, install the [`uglify-js-brunch`](https://github.com/brunch/uglify-js-brunch) plugin:
Para la *build* de producción Brunch más eficiente, instala el plugin [`uglify-js-brunch`](https://github.com/brunch/uglify-js-brunch):

```
# If you use npm
# Si usas npm
npm install --save-dev uglify-js-brunch

# If you use Yarn
# Si usas Yarn
yarn add --dev uglify-js-brunch
```

Then, to create a production build, add the `-p` flag to the `build` command:
Entonces, para crear una *build* de producción, agrega la bandera `-p` al comando `build`:

```
brunch build -p
```

Remember that you only need to do this for production builds. You shouldn't pass the `-p` flag or apply this plugin in development, because it will hide useful React warnings and make the builds much slower.
Recuerda que solo necesitas hacer esto para las *build* de producción. Tú no deberías pasar la bandera `-p` o aplicar el plugin en desarrollo, por que ocultará las advertencias de React y hará las *builds* mucho mas lentas.

### Browserify {#browserify}

For the most efficient Browserify production build, install a few plugins:
Para la *build* de producción con Browserify más eficiente, instala algunos plugins:

```
# If you use npm
# Si usas npm
npm install --save-dev envify uglify-js uglifyify

# If you use Yarn
# Si usas Yarn
yarn add --dev envify uglify-js uglifyify
```
Para crear una *build* de producción, asegúrate de agregar estas transformaciones **(El orden es importante)**:

To create a production build, make sure that you add these transforms **(the order matters)**:

* The [`envify`](https://github.com/hughsk/envify) transform ensures the right build environment is set. Make it global (`-g`).
* The [`uglifyify`](https://github.com/hughsk/uglifyify) transform removes development imports. Make it global too (`-g`).
* Finally, the resulting bundle is piped to [`uglify-js`](https://github.com/mishoo/UglifyJS2) for mangling ([read why](https://github.com/hughsk/uglifyify#motivationusage)).
* La transformación [`envify`](https://github.com/hughsk/envify) asegura que el ambiente de la *build* sea correcto. Hazlo lo global (`-g`).
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* La transformación [`envify`](https://github.com/hughsk/envify) asegura que el ambiente de la *build* sea correcto. Hazlo lo global (`-g`).
* La transformación [`envify`](https://github.com/hughsk/envify) asegura que el ambiente de la *build* sea correcto. Hazlo global (`-g`).

* La transformación [`uglifyify`](https://github.com/hughsk/uglifyify) remueve los import de desarollo. Hazlo global tambien (`-g`).
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
* La transformación [`uglifyify`](https://github.com/hughsk/uglifyify) remueve los import de desarollo. Hazlo global tambien (`-g`).
* La transformación [`uglifyify`](https://github.com/hughsk/uglifyify) remueve los *imports* de desarollo. Hazlo global también (`-g`).

I think we should use the same format for 'imports' as we do for 'build' and others.

* Finalmente, el *bundle* resultante es canalizado a [`uglify-js`](https://github.com/mishoo/UglifyJS2) para mutilar ([Lee porque](https://github.com/hughsk/uglifyify#motivationusage)).

For example:
Por ejemplo:

```
browserify ./index.js \
Expand All @@ -96,30 +94,30 @@ browserify ./index.js \
| uglifyjs --compress --mangle > ./bundle.js
```

>**Note:**
>**Nota:**
>
>The package name is `uglify-js`, but the binary it provides is called `uglifyjs`.<br>
>This is not a typo.
>El nombre del paquete es `uglify-js`, pero el binario que proporciona se llama `uglifyjs`.<br>
>Estoy no es un error de imprenta.

Remember that you only need to do this for production builds. You shouldn't apply these plugins in development because they will hide useful React warnings, and make the builds much slower.
Recuerda que solo necesitas hacer esto para las *builds* de producción. No deberías aplicar estos plugins en desarrollo por que ocultaran las advertencias de React, y haran las *builds* mucho mas lentas.

### Rollup {#rollup}

For the most efficient Rollup production build, install a few plugins:
Para la *build* de producción mas eficiente en Rollup, instala algunos plugins:

```
# If you use npm
# Si usas npm
npm install --save-dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-uglify

# If you use Yarn
# Si usas Yarn
yarn add --dev rollup-plugin-commonjs rollup-plugin-replace rollup-plugin-uglify
```

To create a production build, make sure that you add these plugins **(the order matters)**:
Para crear una *build* de producción, asegúrate de agregar estos plugins **(el orden es importante)**:

* The [`replace`](https://github.com/rollup/rollup-plugin-replace) plugin ensures the right build environment is set.
* The [`commonjs`](https://github.com/rollup/rollup-plugin-commonjs) plugin provides support for CommonJS in Rollup.
* The [`uglify`](https://github.com/TrySound/rollup-plugin-uglify) plugin compresses and mangles the final bundle.
* El plugin [`replace`](https://github.com/rollup/rollup-plugin-replace) asegura que el ambiente correcto para la *build* de producción sea establecido.
* El pluglin [`commonjs`](https://github.com/rollup/rollup-plugin-commonjs) proporciona soporte para CommonJS en Rollup.
* El plugin [`uglify`](https://github.com/TrySound/rollup-plugin-uglify) comprime y mutila el *bundle* final.

```js
plugins: [
Expand All @@ -133,18 +131,18 @@ plugins: [
]
```

For a complete setup example [see this gist](https://gist.github.com/Rich-Harris/cb14f4bc0670c47d00d191565be36bf0).
Para un ejemple de configuración completo [mira este gist](https://gist.github.com/Rich-Harris/cb14f4bc0670c47d00d191565be36bf0).
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Para un ejemple de configuración completo [mira este gist](https://gist.github.com/Rich-Harris/cb14f4bc0670c47d00d191565be36bf0).
Para un ejemplo de configuración completo [mira este gist](https://gist.github.com/Rich-Harris/cb14f4bc0670c47d00d191565be36bf0).


Remember that you only need to do this for production builds. You shouldn't apply the `uglify` plugin or the `replace` plugin with `'production'` value in development because they will hide useful React warnings, and make the builds much slower.
Recuerda que solo necesitas esto para las *builds* de producción. No deberías aplicar el plugin `uglify` o el plugin `replace` con el valor `'production'` en desarrollo, por que esto ocultará las advertencias de React y hará las *builds* mucho más lentas.

### webpack {#webpack}

>**Note:**
>**Nota:**
>
>If you're using Create React App, please follow [the instructions above](#create-react-app).<br>
>This section is only relevant if you configure webpack directly.
>Si estás usando Create React App, por favor sigue [las instrucciones arriba](#create-react-app).<br>
>Esta sección solo es relevante si configuras webpack directamente.

For the most efficient webpack production build, make sure to include these plugins in your production configuration:
Para la *build* de producción más eficiente en webpack, asegúrate de incluir estos plugins en tu configuración de producción:

```js
new webpack.DefinePlugin({
Expand All @@ -153,29 +151,29 @@ new webpack.DefinePlugin({
new webpack.optimize.UglifyJsPlugin()
```

You can learn more about this in [webpack documentation](https://webpack.js.org/guides/production-build/).
Puedes aprender más acerca de esto en la [documentación de webpack](https://webpack.js.org/guides/production-build/).

Remember that you only need to do this for production builds. You shouldn't apply `UglifyJsPlugin` or `DefinePlugin` with `'production'` value in development because they will hide useful React warnings, and make the builds much slower.
Recuerda que solo necesitas hacer para las *builds* de producción. No deberias aplicar `UglifyJsPlugin` o `DefinePlugin` con valor `'production'` en desarrollo, por que ocultaran las advertencias de React y hará las *builds* mucho más lentas.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
Recuerda que solo necesitas hacer para las *builds* de producción. No deberias aplicar `UglifyJsPlugin` o `DefinePlugin` con valor `'production'` en desarrollo, por que ocultaran las advertencias de React y hará las *builds* mucho más lentas.
Recuerda que solo necesitas hacer esto para las *builds* de producción. No deberias aplicar `UglifyJsPlugin` o `DefinePlugin` con valor `'production'` en desarrollo, por que ocultaran las advertencias de React y hará las *builds* mucho más lentas.


## Profiling Components with the Chrome Performance Tab {#profiling-components-with-the-chrome-performance-tab}

In the **development** mode, you can visualize how components mount, update, and unmount, using the performance tools in supported browsers. For example:
En el modo de **desarrollo**, puedes visualizar como montar componentes, actualizarlos y desmontarlos usando las herramientas para rendimiento soportadas por los navegadores. Por ejemplo:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
En el modo de **desarrollo**, puedes visualizar como montar componentes, actualizarlos y desmontarlos usando las herramientas para rendimiento soportadas por los navegadores. Por ejemplo:
En el modo de **desarrollo**, puedes visualizar cómo se montan los componentes, actualizan y desmontan, usando las herramientas para rendimiento soportadas por los navegadores. Por ejemplo:


<center><img src="../images/blog/react-perf-chrome-timeline.png" style="max-width:100%" alt="React components in Chrome timeline" /></center>

To do this in Chrome:
Para hacer esto en Chrome:

1. Temporarily **disable all Chrome extensions, especially React DevTools**. They can significantly skew the results!
1. Temporalmente, **Deshabilita todas la extensiones de Chrome, especialmente React DevTools**, ¡Ellas pueden sesgar significativamente los resultados!

2. Make sure you're running the application in the development mode.
2. Asegúrate de estar ejecutando la aplicación en modo de desarrollo.

3. Open the Chrome DevTools **[Performance](https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/timeline-tool)** tab and press **Record**.
3. Abre la pestaña **[Performance](https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/timeline-tool)** Chrome DevTools y presiona **Record**.

4. Perform the actions you want to profile. Don't record more than 20 seconds or Chrome might hang.
4. Define las acciones que quieres perfilar. No grabes mas de 20 segundos o Chrome podría colgarse.

5. Stop recording.
5. Para de grabar.

6. React events will be grouped under the **User Timing** label.
6. Los eventos de React se agruparan bajo la etiqueta **User Timing**.

For a more detailed walkthrough, check out [this article by Ben Schwarz](https://calibreapp.com/blog/2017-11-28-debugging-react/).

Expand Down