Skip to content

Commit b99097f

Browse files
committed
hydrateRoot refernece
1 parent 73e9661 commit b99097f

File tree

1 file changed

+18
-331
lines changed

1 file changed

+18
-331
lines changed

src/content/reference/react-dom/client/hydrateRoot.md

Lines changed: 18 additions & 331 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ title: hydrateRoot
44

55
<Intro>
66

7-
`hydrateRoot` lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`.](/reference/react-dom/server)
7+
تمكنك `hydrateRoot` من عرض مكونات React في عناصر DOM في المتصفح، التي تم توليدها سابقًا باستخدام [`react-dom/server`](/reference/react-dom/server).
88

99
```js
1010
const root = hydrateRoot(domNode, reactNode, options?)
@@ -16,11 +16,11 @@ const root = hydrateRoot(domNode, reactNode, options?)
1616
1717
---
1818
19-
## Reference {/*reference*/}
19+
## المرجع {/*reference*/}
2020
2121
### `hydrateRoot(domNode, reactNode, options?)` {/*hydrateroot*/}
2222
23-
Call `hydrateRoot` to “attach” React to existing HTML that was already rendered by React in a server environment.
23+
استدعِ `hydrateRoot` لـ "ربط" React بـ HTML الحالي الذي تم عرضه بالفعل بواسطة React في بيئة الخادم.
2424
2525
```js
2626
import { hydrateRoot } from 'react-dom/client';
@@ -29,345 +29,32 @@ const domNode = document.getElementById('root');
2929
const root = hydrateRoot(domNode, reactNode);
3030
```
3131
32-
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 `hydrateRoot` call with its root component.
32+
سيقوم React بربط نفسه بالHTML الموجود داخل الـ `domNode` والاهتمام بإدارة DOM داخلها. التطبيق المبنى كاملًا بواسطة React سيكون لديه عادة استدعاء واحد فقط لـ `hydrateRoot` باستخدام مكوِّن الجذر الخاص به.
3333
34-
[See more examples below.](#usage)
34+
[شاهد المزيد من الأمثلة أدناه.](#usage)
3535
36-
#### Parameters {/*parameters*/}
36+
#### المعاملات {/*parameters*/}
3737
38-
* `domNode`: A [DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that was rendered as the root element on the server.
38+
* `domNode`: عنصر [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Element) الذي تم عرضه كعنصر جذر على الخادم.
3939
40-
* `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 `renderToPipeableStream(<App />)`.
40+
* `reactNode`: "مُكوِّن React" المستخدم لعرض HTML الحالي. هذا عادةً ما يكون جزءًا من JSX مثل `<App />` الذي تم عرضه باستخدام طريقة `ReactDOM Server` مثل `renderToPipeableStream(<App />)`.
4141
42-
* **optional** `options`: An object with options for this React root.
42+
* `options` **اختياري**: كائن يحتوي على خيارات لجذر React هذا.
4343
44-
* **optional** `onRecoverableError`: Callback called when React automatically recovers from errors.
45-
* **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as used on the server.
44+
* `onRecoverableError` **اختياري**: دالة مرجعية تُستدعى تلقائيًا عندما يفيق React من الأخطاء.
45+
* `identifierPrefix` **اختياري**: بادئة نصيّة يستخدمها React للمعرفات الفريدة التي تنشأ عن طريق [`useId`](/reference/react/useId). مفيد لتجنب التعارض عند استخدام العديد من الجذور في نفس الصفحة.
4646
4747
48-
#### Returns {/*returns*/}
48+
#### العائدات {/*returns*/}
4949
50-
`hydrateRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount)
50+
تعيد `hydrateRoot` كائنًا يحتوي على طريقتين: [`render`](#root-render) و [`unmount`.](#root-unmount)
5151
52-
#### Caveats {/*caveats*/}
52+
#### ملاحظات {/*caveats*/}
5353
54-
* `hydrateRoot()` expects the rendered content to be identical with the server-rendered content. You should treat mismatches as bugs and fix them.
55-
* 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.
56-
* You'll likely have only one `hydrateRoot` call in your app. If you use a framework, it might do this call for you.
57-
* If your app is client-rendered with no HTML rendered already, using `hydrateRoot()` is not supported. Use [`createRoot()`](/reference/react-dom/client/createRoot) instead.
54+
* `hydrateRoot()` يتوقع أن يكون المحتوى المعروض مطابقًا تمامًا للمحتوى المرسوم في الخادم. يجب عليك التعامل مع عدم التطابقات على أنها أخطاء وإصلاحها.
55+
* في وضع التطوير، يحذر React من التطابقات أثناء الربط. لا يوجد ضمانات بأن الاختلافات في السمات ستكون مُصحَّحة في حالة التطابقات. هذا مهم لأسباب أداء لأنه في معظم التطبيقات، يكون الاختلافات نادرة، وبالتالي فإن التحقق من صحة جميع العلامات قد يكون صعبًا جدًا.
56+
* من المرجح أن لديك استدعاء واحد فقط لـ `hydrateRoot` في تطبيقك. إذا كنت تستخدم إطار عمل، فقد يستدعيها الإطار نيابةً عنك.
57+
* إذا كان تطبيقك يُرسم في جانب العميل، بدون أي محتوى HTML بالفعل، فاستخدام `hydrateRoot()` ليس مناسبًا. بدلاً من ذلك، استخدم [`createRoot()`](/reference/react-dom/client/createRoot).
5858
5959
---
6060
61-
### `root.render(reactNode)` {/*root-render*/}
62-
63-
Call `root.render` to update a React component inside a hydrated React root for a browser DOM element.
64-
65-
```js
66-
root.render(<App />);
67-
```
68-
69-
React will update `<App />` in the hydrated `root`.
70-
71-
[See more examples below.](#usage)
72-
73-
#### Parameters {/*root-render-parameters*/}
74-
75-
* `reactNode`: A "React node" that you want to update. This will usually be a piece of JSX like `<App />`, but you can also pass a React element constructed with [`createElement()`](/reference/react/createElement), a string, a number, `null`, or `undefined`.
76-
77-
78-
#### Returns {/*root-render-returns*/}
79-
80-
`root.render` returns `undefined`.
81-
82-
#### Caveats {/*root-render-caveats*/}
83-
84-
* If you call `root.render` before the root has finished hydrating, React will clear the existing server-rendered HTML content and switch the entire root to client rendering.
85-
86-
---
87-
88-
### `root.unmount()` {/*root-unmount*/}
89-
90-
Call `root.unmount` to destroy a rendered tree inside a React root.
91-
92-
```js
93-
root.unmount();
94-
```
95-
96-
An app fully built with React will usually not have any calls to `root.unmount`.
97-
98-
This is mostly useful if your React root's DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. You need to tell React to "stop" managing the removed root's content by calling `root.unmount`. Otherwise, the components inside the removed root won't clean up and free up resources like subscriptions.
99-
100-
Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree.
101-
102-
103-
#### Parameters {/*root-unmount-parameters*/}
104-
105-
`root.unmount` does not accept any parameters.
106-
107-
108-
#### Returns {/*root-unmount-returns*/}
109-
110-
`render` returns `null`.
111-
112-
#### Caveats {/*root-unmount-caveats*/}
113-
114-
* Calling `root.unmount` will unmount all the components in the tree and "detach" React from the root DOM node.
115-
116-
* Once you call `root.unmount` you cannot call `root.render` again on the root. Attempting to call `root.render` on an unmounted root will throw a "Cannot update an unmounted root" error.
117-
118-
---
119-
120-
## Usage {/*usage*/}
121-
122-
### Hydrating server-rendered HTML {/*hydrating-server-rendered-html*/}
123-
124-
If your app's HTML was generated by [`react-dom/server`](/reference/react-dom/client/createRoot), you need to *hydrate* it on the client.
125-
126-
```js [[1, 3, "document.getElementById('root')"], [2, 3, "<App />"]]
127-
import { hydrateRoot } from 'react-dom/client';
128-
129-
hydrateRoot(document.getElementById('root'), <App />);
130-
```
131-
132-
This will hydrate the server HTML inside the <CodeStep step={1}>browser DOM node</CodeStep> with the <CodeStep step={2}>React component</CodeStep> for your app. Usually, you will do it once at startup. If you use a framework, it might do this behind the scenes for you.
133-
134-
To hydrate your app, React will "attach" your components' logic to the initial generated HTML from the server. Hydration turns the initial HTML snapshot from the server into a fully interactive app that runs in the browser.
135-
136-
<Sandpack>
137-
138-
```html public/index.html
139-
<!--
140-
HTML content inside <div id="root">...</div>
141-
was generated from App by react-dom/server.
142-
-->
143-
<div id="root"><h1>Hello, world!</h1><button>You clicked me <!-- -->0<!-- --> times</button></div>
144-
```
145-
146-
```js index.js active
147-
import './styles.css';
148-
import { hydrateRoot } from 'react-dom/client';
149-
import App from './App.js';
150-
151-
hydrateRoot(
152-
document.getElementById('root'),
153-
<App />
154-
);
155-
```
156-
157-
```js App.js
158-
import { useState } from 'react';
159-
160-
export default function App() {
161-
return (
162-
<>
163-
<h1>Hello, world!</h1>
164-
<Counter />
165-
</>
166-
);
167-
}
168-
169-
function Counter() {
170-
const [count, setCount] = useState(0);
171-
return (
172-
<button onClick={() => setCount(count + 1)}>
173-
You clicked me {count} times
174-
</button>
175-
);
176-
}
177-
```
178-
179-
</Sandpack>
180-
181-
You shouldn't need to call `hydrateRoot` again or to call it in more places. From this point on, React will be managing the DOM of your application. To update the UI, your components will [use state](/reference/react/useState) instead.
182-
183-
<Pitfall>
184-
185-
The React tree you pass to `hydrateRoot` needs to produce **the same output** as it did on the server.
186-
187-
This is important for the user experience. The user will spend some time looking at the server-generated HTML before your JavaScript code loads. Server rendering creates an illusion that the app loads faster by showing the HTML snapshot of its output. Suddenly showing different content breaks that illusion. This is why the server render output must match the initial render output on the client.
188-
189-
The most common causes leading to hydration errors include:
190-
191-
* Extra whitespace (like newlines) around the React-generated HTML inside the root node.
192-
* Using checks like `typeof window !== 'undefined'` in your rendering logic.
193-
* Using browser-only APIs like [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) in your rendering logic.
194-
* Rendering different data on the server and the client.
195-
196-
React recovers from some hydration errors, but **you must fix them like other bugs.** In the best case, they'll lead to a slowdown; in the worst case, event handlers can get attached to the wrong elements.
197-
198-
</Pitfall>
199-
200-
---
201-
202-
### Hydrating an entire document {/*hydrating-an-entire-document*/}
203-
204-
Apps fully built with React can render the entire document as JSX, including the [`<html>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html) tag:
205-
206-
```js {3,13}
207-
function App() {
208-
return (
209-
<html>
210-
<head>
211-
<meta charSet="utf-8" />
212-
<meta name="viewport" content="width=device-width, initial-scale=1" />
213-
<link rel="stylesheet" href="/styles.css"></link>
214-
<title>My app</title>
215-
</head>
216-
<body>
217-
<Router />
218-
</body>
219-
</html>
220-
);
221-
}
222-
```
223-
224-
To hydrate the entire document, pass the [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Window/document) global as the first argument to `hydrateRoot`:
225-
226-
```js {4}
227-
import { hydrateRoot } from 'react-dom/client';
228-
import App from './App.js';
229-
230-
hydrateRoot(document, <App />);
231-
```
232-
233-
---
234-
235-
### Suppressing unavoidable hydration mismatch errors {/*suppressing-unavoidable-hydration-mismatch-errors*/}
236-
237-
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.
238-
239-
To silence hydration warnings on an element, add `suppressHydrationWarning={true}`:
240-
241-
<Sandpack>
242-
243-
```html public/index.html
244-
<!--
245-
HTML content inside <div id="root">...</div>
246-
was generated from App by react-dom/server.
247-
-->
248-
<div id="root"><h1>Current Date: <!-- -->01/01/2020</h1></div>
249-
```
250-
251-
```js index.js
252-
import './styles.css';
253-
import { hydrateRoot } from 'react-dom/client';
254-
import App from './App.js';
255-
256-
hydrateRoot(document.getElementById('root'), <App />);
257-
```
258-
259-
```js App.js active
260-
export default function App() {
261-
return (
262-
<h1 suppressHydrationWarning={true}>
263-
Current Date: {new Date().toLocaleDateString()}
264-
</h1>
265-
);
266-
}
267-
```
268-
269-
</Sandpack>
270-
271-
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.
272-
273-
---
274-
275-
### Handling different client and server content {/*handling-different-client-and-server-content*/}
276-
277-
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](/reference/react/useState) like `isClient`, which you can set to `true` in an [Effect](/reference/react/useEffect):
278-
279-
<Sandpack>
280-
281-
```html public/index.html
282-
<!--
283-
HTML content inside <div id="root">...</div>
284-
was generated from App by react-dom/server.
285-
-->
286-
<div id="root"><h1>Is Server</h1></div>
287-
```
288-
289-
```js index.js
290-
import './styles.css';
291-
import { hydrateRoot } from 'react-dom/client';
292-
import App from './App.js';
293-
294-
hydrateRoot(document.getElementById('root'), <App />);
295-
```
296-
297-
```js App.js active
298-
import { useState, useEffect } from "react";
299-
300-
export default function App() {
301-
const [isClient, setIsClient] = useState(false);
302-
303-
useEffect(() => {
304-
setIsClient(true);
305-
}, []);
306-
307-
return (
308-
<h1>
309-
{isClient ? 'Is Client' : 'Is Server'}
310-
</h1>
311-
);
312-
}
313-
```
314-
315-
</Sandpack>
316-
317-
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.
318-
319-
<Pitfall>
320-
321-
This approach makes hydration slower because your components have to render twice. Be mindful of the user experience on slow connections. The JavaScript code may load significantly later than the initial HTML render, so rendering a different UI immediately after hydration may also feel jarring to the user.
322-
323-
</Pitfall>
324-
325-
---
326-
327-
### Updating a hydrated root component {/*updating-a-hydrated-root-component*/}
328-
329-
After the root has finished hydrating, you can call [`root.render`](#root-render) to update the root React component. **Unlike with [`createRoot`](/reference/react-dom/client/createRoot), you don't usually need to do this because the initial content was already rendered as HTML.**
330-
331-
If you call `root.render` at some point after hydration, and the component tree structure matches up with what was previously rendered, React will [preserve the state.](/learn/preserving-and-resetting-state) Notice how you can type in the input, which means that the updates from repeated `render` calls every second in this example are not destructive:
332-
333-
<Sandpack>
334-
335-
```html public/index.html
336-
<!--
337-
All HTML content inside <div id="root">...</div> was
338-
generated by rendering <App /> with react-dom/server.
339-
-->
340-
<div id="root"><h1>Hello, world! <!-- -->0</h1><input placeholder="Type something here"/></div>
341-
```
342-
343-
```js index.js active
344-
import { hydrateRoot } from 'react-dom/client';
345-
import './styles.css';
346-
import App from './App.js';
347-
348-
const root = hydrateRoot(
349-
document.getElementById('root'),
350-
<App counter={0} />
351-
);
352-
353-
let i = 0;
354-
setInterval(() => {
355-
root.render(<App counter={i} />);
356-
i++;
357-
}, 1000);
358-
```
359-
360-
```js App.js
361-
export default function App({counter}) {
362-
return (
363-
<>
364-
<h1>Hello, world! {counter}</h1>
365-
<input placeholder="Type something here" />
366-
</>
367-
);
368-
}
369-
```
370-
371-
</Sandpack>
372-
373-
It is uncommon to call [`root.render`](#root-render) on a hydrated root. Usually, you'll [update state](/reference/react/useState) inside one of the components instead.

0 commit comments

Comments
 (0)