Skip to content

Commit f7c624d

Browse files
committed
docs: add hydration debugging guide
1 parent e377252 commit f7c624d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/content/learn/render-and-commit.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,48 @@ export default function App() {
194194
</Sandpack>
195195

196196
This works because during this last step, React only updates the content of `<h1>` with the new `time`. It sees that the `<input>` appears in the JSX in the same place as last time, so React doesn't touch the `<input>`—or its `value`!
197+
## Debugging Hydration Mismatches
198+
199+
Hydration mismatches can occur when the HTML rendered on the server differs from what React renders on the client.
200+
201+
### Common causes
202+
203+
- Non-deterministic values such as:
204+
- `Math.random()`
205+
- `Date.now()`
206+
- Using browser-only APIs like `window` or `document` during render
207+
- Differences between server and client environments
208+
- Asynchronous or inconsistent data
209+
210+
### Example
211+
212+
```jsx
213+
function App() {
214+
return <div>{Math.random()}</div>;
215+
}
216+
```
217+
218+
### How to fix
219+
- Move non-deterministic logic into `useEffect`
220+
- Ensure consistent data between server and client
221+
- Guard browser-specific code:
222+
```jsx
223+
if (typeof window !== "undefined") {
224+
// client-only logic
225+
}
226+
```
227+
228+
### Debugging checklist
229+
- Is the output deterministic?
230+
- Is any browser-only API used during render?
231+
- Is server data identical to client data?
232+
- Are there time-based values?
233+
234+
### Best practices
235+
- Keep rendering logic pure
236+
- Avoid side effects during render
237+
- Use client-only rendering when necessary
238+
197239
## Epilogue: Browser paint {/*epilogue-browser-paint*/}
198240

199241
After rendering is done and React updated the DOM, the browser will repaint the screen. Although this process is known as "browser rendering", we'll refer to it as "painting" to avoid confusion throughout the docs.

0 commit comments

Comments
 (0)