Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.5 — Reuse Patterns: Compound Components, Render Props and HOCs
React · Example 3 of 3

A higher-order component, and the hook that replaces it

Both FAQ items behave the same. In React DevTools the HOC adds a withToggle(FaqItem) layer above FaqItem; the hook version is one component.

Compound components share state through context so related parts can be arranged freely, render props let a component hand data to a function you supply, and higher-order components wrap a component to add props; hooks replaced most render props and HOCs, but each pattern still has a place.

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

Build a compound Accordion with Accordion.Item, Accordion.Header and Accordion.Panel, where only one item is open at a time.

02

Write a withLogger(Component) HOC that logs rendering <Name> every time the wrapped component renders, and set its displayName.

03

Rewrite this render-prop component as a hook: <WindowWidth>{(w) => <p>{w}px</p>}</WindowWidth>.

Explain it without notes

01

What are compound components, and how do the parts share state?

02

What is a render prop? Give an example where it's still the best choice today.

03

What is a higher-order component, and what problems made hooks preferable?

04

For each pattern, name a situation where you would still choose it over a custom hook.

A higher-order component, and the hook that replaces it

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

HOC component name: withToggle(FaqItem)
open answers: 2