Course contentsShow
← React
Lesson 1075 of 2,39627. Composition: Render PropsFree lesson

Migration Pattern: Render Props to Hooks

Step-by-step approach to refactoring render prop components into custom hooks when appropriate.

Migration Pattern: Render Props to Hooks

You'll learn a systematic approach to refactoring render prop components into cleaner, more reusable custom hooks when the use case fits.

The Core Idea

When you have a render prop component that primarily shares stateful logic rather than controlling rendering structure, you can often extract that logic into a custom hook. The migration is straightforward: the logic that was inside the render prop component becomes your hook, and the render function's arguments become the hook's return value.

Step-by-Step Migration

1. Identify the candidate: Look for render prop components where the render function receives data/callbacks but doesn't need rendering control from the provider.

2. Extract the logic: Move the useState, useEffect, and other hook calls from your render prop component into a new useX custom hook.

3. Return the values: Whatever you passed to the render function becomes your hook's return value (object, array, or primitives).

4. Replace usage: In consuming components, call your custom hook instead of rendering the component with a function prop.

Example pattern:

  • Before: <MouseTracker render={(x, y) => <div>{x}, {y}</div>} />
  • After: const { x, y } = useMousePosition(); return <div>{x}, {y}</div>;

When to Migrate

Migrate when the render prop component is used for logic sharing only. Keep render props when you genuinely need the provider to control rendering structure, timing, or conditional behavior that hooks can't manage.

Key Takeaway: Render props that only share stateful logic can be migrated to custom hooks by extracting the internal logic and returning the values previously passed to the render function—resulting in cleaner, more composable code.