Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.6 — Working with Non-React Code
React · Example 3 of 3

flushSync: update the DOM before scrolling

Without flushSync the handler still sees the old list, so it scrolls to Good and the new message stays hidden. With it, the new <li> is already in the DOM. Click Send a few times in each box to feel the difference.

To use a widget that wasn't built for React (a chart, a map, an editor), give it a DOM node through a ref, create it in an effect, keep it in sync with props in another effect and destroy it in the cleanup; use flushSync only when you must read the updated DOM right after a state change.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Wrap this class in a Ticker component: class Ticker { constructor(el) { this.el = el; } start(text) { this.el.textContent = text; } stop() { this.el.textContent = ""; } }. The component takes a text prop and must call start whenever it changes and stop on unmount.

02

Write a todo list where Add appends an item and then focuses the new item's input in the same handler.

Explain it without notes

01

How do you wrap a non-React widget, such as a chart library, in a React component?

02

Why split the widget's creation and its updates into two effects?

03

What does flushSync do, when do you need it, and why should it be rare?

04

How do events from the widget reach React without recreating the widget when the callback changes?

flushSync: update the DOM before scrolling

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

without flushSync, last item is: Good
with flushSync, last item is: Message 6