Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 41 additions & 41 deletions beta/src/content/apis/react-dom/hydrate.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
---
title: hydrate
título: hydrate
---
<Pitfall>

In React 18, `hydrate` was replaced by [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot) Using `hydrate` in React 18 will warn that your app will behave as if it’s running React 17. Learn more [here.](https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-client-rendering-apis)
En React 18, `hydrate` fue sustituido por [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot) El uso de `hydrate` en React 18 advertirá que tu aplicación se comportará como si estuviera ejecutando React 17. Más información [here.](https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#updates-to-client-rendering-apis)

</Pitfall>

<Intro>

`hydrate` lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`](/apis/react-dom/server) in React 17 and below.
`hydrate` permite mostrar componentes React dentro de un nodo DOM del navegador cuyo contenido HTML ha sido generado previamente por [`react-dom/server`](/apis/react-dom/server) en React 17 y posteriores.

```js
hydrate(reactNode, domNode, callback?)
Expand All @@ -21,23 +21,23 @@ hydrate(reactNode, domNode, callback?)

---

## Usage {/*usage*/}
## Uso {/*usage*/}

Call `hydrate` to attach a <CodeStep step={1}>React component</CodeStep> into a server-rendered <CodeStep step={2}>browser DOM node</CodeStep>.
Llama a `hydrate` para unir un <CodeStep step={1}>componente React</CodeStep> en un <CodeStep step={2}>nodo DOM del navegador</CodeStep> renderizado por el servidor.

```js [[1, 3, "document.getElementById('root')"], [2, 3, "<App />"]]
import {hydrate} from 'react-dom';

hydrate(<App />, document.getElementById('root'));
````

Using `hydrate()` to render a client-only app (an app without server-rendered HTML) is not supported. Use [`render()`](/apis/react-dom/render) (in React 17 and below) or [`createRoot()`](/apis/react-dom/client/createRoot) (in React 18+) instead.
Utilizando `hydrate()` para hacer una aplicación sólo para clientes (una aplicación sin HTML renderizado en el servidor) no es compatible. Utilice [`render()`](/apis/react-dom/render) (en React 17 e inferior) o [`createRoot()`](/apis/react-dom/client/createRoot) (en React 18+) en su lugar.

### Hydrating server-rendered HTML {/*hydrating-server-rendered-html*/}
### Hydrating HTML renderizado por el servidor {/*hydrating-server-rendered-html*/}

In React, "hydration" is how React "attaches" to existing HTML that was already rendered by React in a server environment. During hydration, React will attempt to attach event listeners to the existing markup and take over rendering the app on the client.
En React, "hydration" es la forma en que React se "adhiere" al HTML existente que ya fue renderizado por React en un entorno de servidor. Durante (hydration), React intentará adjuntar escuchas de eventos al marcado existente y se encargará de renderizar la aplicación en el cliente.

In apps fully built with React, **you will usually only hydrate one "root", once at startup for your entire app**.
En las aplicaciones totalmente construidas con React, **sólo se hidratará (hydrate) un "root", una vez al inicio para toda la aplicación**.

<Sandpack>

Expand All @@ -46,7 +46,7 @@ In apps fully built with React, **you will usually only hydrate one "root", once
HTML content inside <div id="root">...</div>
was generated from App by react-dom/server.
-->
<div id="root"><h1>Hello, world!</h1></div>
<div id="root"><h1>Hola, mundo!</h1></div>
```

```js index.js active
Expand All @@ -59,23 +59,23 @@ hydrate(<App />, document.getElementById('root'));

```js App.js
export default function App() {
return <h1>Hello, world!</h1>;
return <h1>Hola, mundo!</h1>;
}
```

</Sandpack>

Usually you shouldn't need to call `hydrate` again or to call it in more places. From this point on, React will be managing the DOM of your application. If you want to update the UI, your components can do this by [using state.](/apis/react/useState)
Normalmente no deberías necesitar llamar a `hydrate` de nuevo o llamarlo en más sitios. A partir de este punto, React gestionará el DOM de tu aplicación. Si quieres actualizar la UI, tus componentes pueden hacerlo [usando state].(/apis/react/useState)

For more information on hydration, see the docs for [`hydrateRoot`.](/apis/react-dom/client/hydrateRoot)
Para más información sobre hydration, consulte la documentación de [`hydrateRoot`].(/apis/react-dom/client/hydrateRoot)

---

### Unavoidable hydration mismatches {/*avoiding-unavoidable-hydration-mismatches*/}
### Errores inevitables de hydration {/*avoiding-unavoidable-hydration-mismatches*/}

If a single element’s attribute or text content is unavoidably different between the server and the client (for example, a timestamp), you may silence the hydration mismatch warning.
Si el contenido del atributo o del texto de un solo elemento es inevitablemente diferente entre el servidor y el cliente (por ejemplo, una marca de tiempo), puede silenciar la advertencia de error de hydration.

To silence hydration warnings on an element, add `suppresshydrationWarning={true}`:
Para silenciar los avisos de hydration en un elemento, añada `suppresshydrationWarning={true}`:

<Sandpack>

Expand All @@ -84,7 +84,7 @@ To silence hydration warnings on an element, add `suppresshydrationWarning={true
HTML content inside <div id="root">...</div>
was generated from App by react-dom/server.
-->
<div id="root"><h1>Current Date: 01/01/2020</h1></div>
<div id="root"><h1>Fecha actual: 01/01/2020</h1></div>
```

```js index.js
Expand All @@ -100,7 +100,7 @@ export default function App() {
return (
<>
<h1 suppressHydrationWarning={true}>
Current Date: {new Date().toLocaleDateString()}
Fecha actual: {new Date().toLocaleDateString()}
</h1>
</>
);
Expand All @@ -109,18 +109,18 @@ export default function App() {

</Sandpack>

This only works one level deep, and is intended to be an escape hatch. Don’t overuse it. Unless it’s text content, React still won’t attempt to patch it up, so it may remain inconsistent until future updates.
Esto sólo funciona a un nivel de profundidad, y pretende ser una escotilla de escape. No lo utilices en exceso. A menos que se trate de contenido de texto, React todavía no intentará parchearlo, por lo que puede permanecer inconsistente hasta futuras actualizaciones.

### Handling different client and server content {/*handling-different-client-and-server-content*/}
### Manejo de diferentes contenidos del cliente y del servidor {/*handling-different-client-and-server-content*/}

If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a [state variable](/apis/react/useState) like `isClient`, which you can set to `true` in an [effect](/apis/react/useEffect):
Si necesitas intencionadamente renderizar algo diferente en el servidor y en el cliente, puedes hacer un renderizado de dos pasos. Los componentes que renderizan algo diferente en el cliente pueden leer una [variable de estado](/apis/react/useState) como `isClient`, que puedes establecer como `true` en un [effect](/apis/react/useEffect):

<Sandpack>

```html public/index.html
<!--
HTML content inside <div id="root">...</div>
was generated from App by react-dom/server.
Contenido HTML dentro de <div id="root">...</div>
se generó a partir de App mediante react-dom/server.
-->
<div id="root"><h1>Is Server</h1></div>
```
Expand All @@ -145,56 +145,56 @@ export default function App() {

return (
<h1>
{isClient ? 'Is Client' : 'Is Server'}
{isClient ? 'Es Cliente' : 'Es Servidor'}
</h1>
);
}
```

</Sandpack>

This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration.
De esta forma, el pase inicial de renderizado renderizará el mismo contenido que el servidor, evitando errores, pero un pase adicional ocurrirá de forma sincronizada justo después de hydration.

<Pitfall>

This approach will make your components slower because they have to render twice, so use it with caution.
Este enfoque hará que tus componentes sean más lentos porque tienen que renderizar dos veces, así que úsalo con precaución.

Remember to be mindful of user experience on slow connections. The JavaScript code may load significantly later than the initial HTML render, so if you render something different in the client-only pass, the transition can be jarring. However, if executed well, it may be beneficial to render a “shell” of the application on the server, and only show some of the extra widgets on the client. To learn how to do this without getting the markup mismatch issues, refer to the explanation in the previous paragraph.
Recuerda que debes tener en cuenta la experiencia del usuario en conexiones lentas. El código JavaScript puede cargarse significativamente más tarde que el renderizado inicial del HTML, por lo que si se renderiza algo diferente en el pase del cliente, la transición puede ser discordante. Sin embargo, si se ejecuta bien, puede ser beneficioso renderizar un "shell" de la aplicación en el servidor, y sólo mostrar algunos de los widgets adicionales en el cliente. Para saber cómo hacer esto sin tener problemas de errores de marcado, consulte la explicación del párrafo anterior.

</Pitfall>



## Reference {/*reference*/}
## Referencia {/*reference*/}

### `hydrate(reactNode, domNode, callback?)` {/*hydrate-root*/}

Call `hydrate` in React 17 and below to “attach” React to existing HTML that was already rendered by React in a server environment.
Llame a `hydrate` en React 17 y por debajo para "unir" React al HTML existente que ya fue renderizado por React en un entorno de servidor.

```js
hydrate(reactNode, domNode);
```

React will attach to the HTML that exists inside the `domNode`, and take over managing the DOM inside it. An app fully built with React will usually only have one `hydrate` call with its root component.
React se unirá al HTML que existe dentro del `domNode`, y se encargará de gestionar el DOM dentro de él. Una aplicación completamente construida con React normalmente sólo tendrá una llamada a `hydrate` con su componente raíz.

[See examples above.](#usage)
[Vea los ejemplos anteriores.](#usage)

#### Parameters {/*parameters*/}
#### Parámetros {/*parameters*/}

* `reactNode`: The "React node" used to render the existing HTML. This will usually be a piece of JSX like `<App />` which was rendered with a `ReactDOM Server` method such as `renderToString(<App />)` in React 17.
* `reactNode`: El "nodo React" utilizado para renderizar el HTML existente. Normalmente será un elemento JSX como `<App />` que se renderizó con un método `ReactDOM Server` como `renderToString(<App />)` en React 17.

* `domNode`: A [DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that was rendered as the root element on the server.
* `domNode`: Un [elemento DOM](https://developer.mozilla.org/es/docs/Web/API/Element) que se ha representado como elemento raíz en el servidor.

* **optional**: `callback`: A function. If passed, React will call it after your component is hydrated.
* **optional**: `callback`: Es una función. Si se pasa, React la llamará después de que su componente haya llamado hydrated.

#### Returns {/*returns*/}

`hydrate` returns null.
`hydrate` Devuelve null.

#### Caveats {/*caveats*/}
* `hydrate` expects the rendered content to be identical with the server-rendered content. React can patch up differences in text content, but you should treat mismatches as bugs and fix them.
* In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive.
* You'll likely have only one `hydrate` call in your app. If you use a framework, it might do this call for you.
* If your app is client-rendered with no HTML rendered already, using `hydrate()` is not supported. Use [render()](/apis/react-dom/render) (for React 17 and below) or [createRoot()](/apis/react-dom/client/createRoot) (for React 18+) instead.
#### Advertencias {/*caveats*/}
* `hydrate` espera que el contenido renderizado sea idéntico al contenido renderizado por el servidor. React puede parchear las diferencias en el contenido del texto, pero debes tratar los errores de compatibilidad como si se tratara un error y solucionarlos.
* En el modo de desarrollo, React avisa de las incompatibilidades durante hydration. No hay garantías de que las diferencias de atributos sean parcheadas en caso de incompatibilidad. Esto es importante por razones de rendimiento, ya que en la mayoría de las aplicaciones, las incompatibilidades son raras, por lo que validar todo el código sería excesivamente complicado.
* Es probable que sólo tengas una llamada a "hidrate" en tu aplicación. Si utilizas un framework, es posible que haga esta llamada por ti.
* Si tu aplicación está renderizada por el cliente y no tiene HTML renderizado, el uso de `hydrate()` no está permitido. Utiliza [render()](/apis/react-dom/render) (para React 17 e inferior) o [createRoot()](/apis/react-dom/client/createRoot) (para React 18+) en su lugar.

---