Command Palette

Search for a command to run...

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

A vanilla widget that talks back to React

Two directions, one source of truth. A click in the widget calls onChange, React state changes, and the sync effect tells the widget. A change from React (Clear) goes through the same effect.

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?

A vanilla widget that talks back to React

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

widget shows 3
widget shows 5
You rated it 5 / 5
widget shows 0