Render Prop Pattern
Share stateful logic between components using the render prop pattern for maximum flexibility.
import { useState, useEffect } from 'react';
interface MousePosition {
x: number;
y: number;
}
export function MouseTracker({
render,
}: {
render: (pos: MousePosition) => React.ReactNode;
}) {
const [pos, setPos] = useState<MousePosition>({ x: 0, y: 0 });
useEffect(() => {
const handler = (e: MouseEvent) => setPos({ x: e.clientX, y: e.clientY });
window.addEventListener('mousemove', handler);
return () => window.removeEventListener('mousemove', handler);
}, []);
return <>{render(pos)}</>;
}
// Usage:
// <MouseTracker render={({ x, y }) => <span>({x}, {y})</span>} />Use Cases
- Mouse tracking
- Toggle logic sharing
- Data fetching wrappers
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Compound Component Pattern
Build flexible compound components using React Context for implicit parent-child communication.
Multi-Zone Application Setup
Compose multiple Next.js apps under one domain using rewrites for micro-frontend architecture.
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.