Course contentsShow
← React
Lesson 322 of 2,3969. Class Components (Legacy Overview)Free lesson

From Render Props Pattern to Custom Hooks

Refactor class-based render prop components into reusable custom hooks that return state and handlers.

From Render Props Pattern to Custom Hooks

What you'll learn: How to modernize class-based render prop components into cleaner, more reusable custom hooks.

The Evolution from Render Props

In class components, the render props pattern solved the problem of sharing stateful logic between components. You'd create a class that managed state and lifecycle methods, then passed data through a function prop:

// Old: Class with render prop
class MouseTracker extends React.Component {
  state = { x: 0, y: 0 };

  componentDidMount() {
    document.addEventListener('mousemove', this.handleMove);
  }

  componentWillUnmount() {
    document.removeEventListener('mousemove', this.handleMove);
  }

  handleMove = (e) => {
    this.setState({ x: e.clientX, y: e.clientY });
  };

  render() {
    return this.props.render(this.state);
  }
}

// Usage:
<MouseTracker render={({ x, y }) => <p>Mouse at {x}, {y}</p>} />

The Custom Hook Alternative

Custom hooks extract this same logic into a simple function that returns values:

// Modern: Custom hook
function useMousePosition() {
  const [position, setPosition] = React.useState({ x: 0, y: 0 });

  React.useEffect(() => {
    const handleMove = (e) => {
      setPosition({ x: e.clientX, y: e.clientY });
    };

    document.addEventListener('mousemove', handleMove);
    return () => document.removeEventListener('mousemove', handleMove);
  }, []);

  return position;
}

// Usage:
function MyComponent() {
  const { x, y } = useMousePosition();
  return <p>Mouse at {x}, {y}</p>;
}

Why This Matters

Hooks eliminate the wrapper component entirely. The logic goes from being a component that wraps your UI to a function that returns data. No more render prop nesting, no more classes—just straightforward function calls.

Key Takeaway: Custom hooks are the modern replacement for render props—they extract stateful logic into reusable functions that return state and handlers directly, without requiring wrapper components.