From bdcd84a4d70d487a33328ca23a45206d0327da31 Mon Sep 17 00:00:00 2001 From: Nahuel Clotet Date: Tue, 2 May 2023 19:17:11 -0300 Subject: [PATCH 1/4] Translate Synchronizing-with-effects to Spanish --- .../learn/synchronizing-with-effects.md | 552 +++++++++--------- src/sidebarLearn.json | 4 +- 2 files changed, 278 insertions(+), 278 deletions(-) diff --git a/src/content/learn/synchronizing-with-effects.md b/src/content/learn/synchronizing-with-effects.md index 24b9f9eb1..ac13ea104 100644 --- a/src/content/learn/synchronizing-with-effects.md +++ b/src/content/learn/synchronizing-with-effects.md @@ -1,97 +1,97 @@ --- -title: 'Synchronizing with Effects' +title: 'Sincronizar con efectos' --- -Some components need to synchronize with external systems. For example, you might want to control a non-React component based on the React state, set up a server connection, or send an analytics log when a component appears on the screen. *Effects* let you run some code after rendering so that you can synchronize your component with some system outside of React. +Algunos componentes tienen la necesidad de sincronizarse con sistemas externos. Por ejemplo, es posible que desees controlar un componente que no sea de React en función a un estado de React, configurar una conexión de servidor, o enviar un registro de análisis cuando un componente se muestra en la pantalla. Los *Efectos* te permiten ejecutar código después del renderizado para que puedas sincronizar tu componente con un sistema fuera de React. -- What Effects are -- How Effects are different from events -- How to declare an Effect in your component -- How to skip re-running an Effect unnecessarily -- Why Effects run twice in development and how to fix them +- Que son los Efectos +- Cómo se diferencian los Efectos de los eventos +- Cómo declarar un Efecto en tu componente +- Cómo evitar que un Efecto se vuelva a ejecutar innecesariamente +- Por qué los Efectos se ejecutan dos veces en desarrollo y cómo arreglarlo -## What are Effects and how are they different from events? {/*what-are-effects-and-how-are-they-different-from-events*/} +## Que son los efectos y en que se diferencian de los eventos? {/*what-are-effects-and-how-are-they-different-from-events*/} -Before getting to Effects, you need to be familiar with two types of logic inside React components: +Antes de empezar con los Efectos, necesitas familiarizarte con dos tipos de lógica dentro de los componentes de React: -- **Rendering code** (introduced in [Describing the UI](/learn/describing-the-ui)) lives at the top level of your component. This is where you take the props and state, transform them, and return the JSX you want to see on the screen. [Rendering code must be pure.](/learn/keeping-components-pure) Like a math formula, it should only _calculate_ the result, but not do anything else. +- **Código renderizado** (introducido en [Describir la UI](/learn/describing-the-ui)) se encuentra en el nivel superior de tu componente. Aquí es donde tomas las props y el estado, los modificas, y se devuelve el JSX que se desea ver en la pantalla. [El código renderizado debe ser puro.](/learn/keeping-components-pure) Como si fuese una fórmula matemática, sólo debe _calcular_ el resultado, y no hacer nada más. -- **Event handlers** (introduced in [Adding Interactivity](/learn/adding-interactivity)) are nested functions inside your components that *do* things rather than just calculate them. An event handler might update an input field, submit an HTTP POST request to buy a product, or navigate the user to another screen. Event handlers contain ["side effects"](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) (they change the program's state) caused by a specific user action (for example, a button click or typing). +- **Manejadores de eventos** (introducido en [Añadir interactividad](/learn/adding-interactivity)) son funciones anidadas dentro de tus componentes que *hacen* cosas en lugar de solo calcularlas. Un manejador de eventos podría actualizar un campo de un formulario, enviar una solicitud HTTP POST para comprar un producto, o hacer que el usuario navegue hacia otra pantalla. Los manejadores de eventos contienen ["efectos secundarios"](https://es.wikipedia.org/wiki/Efecto_secundario_(inform%C3%A1tica)) (Pueden cambiar el estado del programa) causado por una acción específica del usuario (por ejemplo, al hacer clic en un botón o al escribir). -Sometimes this isn't enough. Consider a `ChatRoom` component that must connect to the chat server whenever it's visible on the screen. Connecting to a server is not a pure calculation (it's a side effect) so it can't happen during rendering. However, there is no single particular event like a click that causes `ChatRoom` to be displayed. +A veces, esto no es suficiente. Considera un componente `ChatRoom` que debe conectarse al servidor del chat cada vez que esté visible en pantalla. Conectarse al servidor no es un cálculo puro (es un efecto secundario), por lo que no puede suceder durante el renderizado. Sin embargo, no hay un evento particular como un clic que haga que `ChatRoom` se muestre en pantalla. -***Effects* let you specify side effects that are caused by rendering itself, rather than by a particular event.** Sending a message in the chat is an *event* because it is directly caused by the user clicking a specific button. However, setting up a server connection is an *Effect* because it should happen no matter which interaction caused the component to appear. Effects run at the end of a [commit](/learn/render-and-commit) after the screen updates. This is a good time to synchronize the React components with some external system (like network or a third-party library). +**Los *Efectos* te permiten especificar efectos secundarios que son causados por el renderizado en sí mismo, en lugar de por un evento particular.** Enviar un mensaje en el chat es un *evento* porque es directamente causado por el usuario haciendo clic en un botón. Sin embargo, establecer una conexión a un servidor es un *Efecto* porque debería suceder sin importar qué interacción causó que el componente apareciera. Los efectos se ejecutan al final de la [confirmación](/learn/render-and-commit), después de que la pantalla se actualice. Este es un buen momento para sincronizar los componentes de React con algún sistema externo (como una red o una biblioteca de terceros). -Here and later in this text, capitalized "Effect" refers to the React-specific definition above, i.e. a side effect caused by rendering. To refer to the broader programming concept, we'll say "side effect". +A partir de ahora en este texto, "Efecto" en mayúsculas se refiere a la definición específica de React mencionada anteriormente, es decir, un efecto secundario causado por el renderizado. Para referirnos al concepto de programación más amplio, diremos "efecto secundario". -## You might not need an Effect {/*you-might-not-need-an-effect*/} +## Quizás no necesites un Efecto {/*you-might-not-need-an-effect*/} -**Don't rush to add Effects to your components.** Keep in mind that Effects are typically used to "step out" of your React code and synchronize with some *external* system. This includes browser APIs, third-party widgets, network, and so on. If your Effect only adjusts some state based on other state, [you might not need an Effect.](/learn/you-might-not-need-an-effect) +**No te apresures en añadir Efectos en tus componentes.** Ten en cuenta que los Efectos se usan típicamente para "salir" de tu código React y sincronizar con algún sistema *externo*. Esto incluye APIs del navegador, widgets de terceros, red, etc. Si tu efecto solo ajusta un estado basado en otro estado, [quizás no necesites un Efecto.](/learn/you-might-not-need-an-effect) -## How to write an Effect {/*how-to-write-an-effect*/} +## Cómo escribir un Efecto {/*how-to-write-an-effect*/} -To write an Effect, follow these three steps: +Para escribir un Efecto, sigue los siguientes pasos: -1. **Declare an Effect.** By default, your Effect will run after every render. -2. **Specify the Effect dependencies.** Most Effects should only re-run *when needed* rather than after every render. For example, a fade-in animation should only trigger when a component appears. Connecting and disconnecting to a chat room should only happen when the component appears and disappears, or when the chat room changes. You will learn how to control this by specifying *dependencies.* -3. **Add cleanup if needed.** Some Effects need to specify how to stop, undo, or clean up whatever they were doing. For example, "connect" needs "disconnect", "subscribe" needs "unsubscribe", and "fetch" needs either "cancel" or "ignore". You will learn how to do this by returning a *cleanup function*. +1. **Declara un Efecto.** Por defecto, tu Efecto se ejecutará después de cada renderizado. +2. **Define las dependencias del Efecto.** La mayoría de los Efectos solo deben volver a ejecutarse *cuando sea necesario* en lugar de hacerlo después de cada renderizado. Por ejemplo, una animación de desvanecimiento solo debe desencadenarse cuando aparece el componente. La conexión y desconexión a una sala de chat solo debe suceder cuando el componente aparece y desaparece, o cuando cambia la sala de chat. Aprenderás cómo controlar esto especificando las *dependencias*. +3. **Añade limpieza si es necesario.** Algunos Efectos necesitan especificar como detener, deshacer, o limpiar cualquier cosa que estaban haciendo. Por ejemplo, "conectar" necesita "desconectar", "suscribirse" necesita "anular suscripción" y "buscar" necesita "cancelar" o "ignorar". Aprenderás cómo hacer esto devolviendo una *función de limpieza* -Let's look at each of these steps in detail. +Veamos cada uno de estos pasos en detalle. -### Step 1: Declare an Effect {/*step-1-declare-an-effect*/} +### Paso 1: Declara un Efecto {/*step-1-declare-an-effect*/} -To declare an Effect in your component, import the [`useEffect` Hook](/reference/react/useEffect) from React: +Para declarar un efecto en tu componente, importa el [`useEffect` Hook](/reference/react/useEffect) desde React: ```js import { useEffect } from 'react'; ``` -Then, call it at the top level of your component and put some code inside your Effect: +Luego, llámalo en el nivel superior de tu componente y escribe algún código dentro del Efecto: ```js {2-4} function MyComponent() { useEffect(() => { - // Code here will run after *every* render + // El código aquí se ejecutará después de *cada* renderizado }); return
; } ``` -Every time your component renders, React will update the screen *and then* run the code inside `useEffect`. In other words, **`useEffect` "delays" a piece of code from running until that render is reflected on the screen.** +Cada vez que el componente se renderiza, React actualizará la pantalla *y entonces* ejecutará el código dentro de `useEffect`. En otras palabras, **`useEffect` "retrasa" la ejecución de una parte del código hasta que el renderizado es reflejado en la pantalla.** -Let's see how you can use an Effect to synchronize with an external system. Consider a `` React component. It would be nice to control whether it's playing or paused by passing an `isPlaying` prop to it: +Veamos como puedes usar un Efecto para sincronizarlo con un sistema externo. Considera un componente de React ``. Sería bueno controlar si está reproduciéndose o en pausa, enviándole la prop `isPlaying`: ```js ; ``` -Your custom `VideoPlayer` component renders the built-in browser [`