Advanced Hooks
Performance Optimization with useMemo and useCallback
useMemo Core Mechanism:
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);- Dependency Array: Recomputes only when dependencies change.
- Caching Principle: Based on shallow comparison of dependencies.
- Use Cases: Complex computations, preventing unnecessary child component renders.
useCallback Core Mechanism:
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);- Function Memoization: Returns the same function reference if dependencies are unchanged.
- Child Component Optimization: Works with
React.memoto avoid unnecessary renders. - Typical Scenarios: Event handlers, callbacks passed to child components.
Performance Comparison Example:
// Unoptimized Version - Creates new function on every render
function Parent() {
const handleClick = () => console.log('Click');
return <Child onClick={handleClick} />;
}
// Optimized Version - Uses useCallback to maintain stable function reference
function Parent() {
const handleClick = useCallback(() => console.log('Click'), []);
return <Child onClick={handleClick} />;
}useRef Usage and Considerations
Basic Usage:
const refContainer = useRef(initialValue);- DOM References: Access DOM nodes.
- Persistent Values: Store mutable values across render cycles.
- Difference from State: Modifying ref does not trigger re-renders.
Typical Use Cases:
// 1. DOM Manipulation
function TextInput() {
const inputRef = useRef(null);
const focusInput = () => inputRef.current.focus();
return <input ref={inputRef} />;
}
// 2. Storing Previous Value
function Counter() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count;
});
const prevCount = prevCountRef.current;
return <div>Now: {count}, Before: {prevCount}</div>;
}Considerations:
- Avoid Overuse: Prioritize React state management.
- Async Risks: Ref values may be inconsistent between renders.
- Function Component Limitations: Cannot directly replace class instance properties.
useImperativeHandle with forwardRef
Combined Usage Pattern:
const FancyInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => inputRef.current.focus(),
scrollTo: () => inputRef.current.scrollIntoView()
}));
return <input ref={inputRef} {...props} />;
});
// Parent Component Usage
function Parent() {
const inputRef = useRef();
return (
<>
<FancyInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
</>
);
}Implementation Principle:
forwardRef: Forwards the parent’s ref to the child component.useImperativeHandle: Customizes the instance value exposed to the parent.- Type Safety: Works with TypeScript to define clear interfaces.
useLayoutEffect vs. useEffect
Execution Timing Comparison:
| Feature | useEffect | useLayoutEffect |
|---|---|---|
| Execution Phase | After browser paint | After DOM update, before browser paint |
| Use Cases | Data fetching, subscriptions | Synchronous DOM operations |
| Blocks Rendering | No | Yes |
| Server-Side Rendering | Supported | Warns (avoid use) |
Typical Use Cases:
// useEffect - Asynchronous Operations
useEffect(() => {
fetchData().then(data => setData(data));
}, []);
// useLayoutEffect - Synchronous DOM Measurement
useLayoutEffect(() => {
const width = element.current.offsetWidth;
setDimensions({ width });
}, [deps]);Custom Hook Design Patterns
Data Fetching Pattern:
function useFetch(url, options) {
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url, options);
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, [url, options]);
return { data, error, loading };
}Subscription Pattern:
function useSubscription(eventBus, eventName, callback) {
useEffect(() => {
eventBus.subscribe(eventName, callback);
return () => eventBus.unsubscribe(eventName, callback);
}, [eventBus, eventName, callback]);
}Design Principles:
- Single Responsibility: Each Hook focuses on a specific function.
- Composability: Supports combination with other Hooks.
- Clear Dependencies: Correctly declare all dependencies.
- Type Safety: Use TypeScript for clear interfaces.
Component Performance Optimization
Virtual DOM and Diff Algorithm Optimization
React Diff Strategies:
- Tree Comparison: Compares same-level nodes; cross-level moves are costly.
- Component Type: Different types result in destruction and recreation.
- Key Property: Unique identifier for list items.
Optimization Tips:
// Bad Practice - Creates new array on every render
function BadList() {
const items = Array(1000).fill().map((_, i) => i);
return <List items={items} />;
}
// Good Practice - Stable reference
function GoodList() {
const items = useMemo(() => Array(1000).fill().map((_, i) => i), []);
return <List items={items} />;
}React.memo and PureComponent
React.memo Implementation:
const MemoizedComponent = React.memo(function MyComponent(props) {
/* Render logic */
}, arePropsEqual);
// Custom comparison function
function arePropsEqual(prevProps, nextProps) {
return prevProps.id === nextProps.id;
}PureComponent Principle:
- Automatically performs shallow comparison of props and state.
- Suitable for class components.
- Avoids manual
shouldComponentUpdateimplementation.
Usage Scenario Comparison:
| Scenario | React.memo | PureComponent |
|---|---|---|
| Component Type | Function components | Class components |
| Comparison Control | Custom comparison function | Default shallow comparison |
| Applicable Version | React 16.6+ | All versions |
List Rendering Optimization
Key Selection Principles:
- Stability: Unique identifiers that don’t change across renders.
- Predictability: Same input produces the same key.
- Avoid Index: Avoid using array indices for dynamic lists.
Virtual List Implementation:
import { FixedSizeList as List } from 'react-window';
function BigList({ items }) {
return (
<List
height={600}
itemCount={items.length}
itemSize={50}
width="100%"
>
{({ index, style }) => (
<div style={style}>
{items[index].name}
</div>
)}
</List>
);
}Optimization Techniques:
- Pagination loading.
- Windowed rendering (react-window).
- Avoid inline functions.
- Use CSS containment.
Code Splitting and Lazy Loading
React.lazy Implementation:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<LazyComponent />
</Suspense>
);
}Route-Level Code Splitting:
const Home = React.lazy(() => import('./routes/Home'));
const About = React.lazy(() => import('./routes/About'));
function App() {
return (
<Router>
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
</Router>
);
}Preloading Strategy:
// Preload on hover
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function HoverLoader() {
const [preload, setPreload] = useState(false);
return (
<div
onMouseEnter={() => setPreload(true)}
onMouseLeave={() => setPreload(false)}
>
{preload && <LazyComponent />}
</div>
);
}Memory Leaks and Resource Cleanup
Common Leak Scenarios:
- Uncleaned timers.
- Uncancelled subscriptions.
- Unreleased DOM events.
- Unaborted Promises.
Cleanup Pattern Examples:
// Timer Cleanup
useEffect(() => {
const timer = setInterval(() => {
// ...
}, 1000);
return () => clearInterval(timer);
}, []);
// Subscription Cleanup
useEffect(() => {
const subscription = eventBus.subscribe(callback);
return () => subscription.unsubscribe();
}, []);
// AbortController for Request Cancellation
useEffect(() => {
const controller = new AbortController();
fetch(url, { signal: controller.signal })
.then(/* ... */)
.catch(e => {
if (e.name !== 'AbortError') {
// Handle real errors
}
});
return () => controller.abort();
}, [url]);Higher-Order Components and Render Props
Definition and Implementation of Higher-Order Components (HOC)
Basic HOC Pattern:
function withLogging(WrappedComponent) {
return function EnhancedComponent(props) {
console.log('Props:', props);
return <WrappedComponent {...props} />;
};
}
// Usage
const EnhancedComponent = withLogging(MyComponent);Parameterized HOC:
function withDataFetching(url) {
return function(WrappedComponent) {
return function EnhancedComponent(props) {
const [data, setData] = useState(null);
useEffect(() => {
fetchData(url).then(setData);
}, [url]);
return <WrappedComponent data={data} {...props} />;
};
};
}HOC Use Cases
Typical Applications:
- Authorization Control:
function withAuth(WrappedComponent) {
return function AuthenticatedComponent(props) {
const { user } = useAuth();
return user ? <WrappedComponent {...props} /> : <Redirect to="/login" />;
};
}- Performance Monitoring:
function withPerformance(WrappedComponent) {
return function MonitoredComponent(props) {
const start = performance.now();
useEffect(() => {
const duration = performance.now() - start;
logRenderTime(WrappedComponent.name, duration);
}, []);
return <WrappedComponent {...props} />;
};
}- Theme Injection:
function withTheme(WrappedComponent) {
return function ThemedComponent(props) {
const theme = useTheme();
return <WrappedComponent theme={theme} {...props} />;
};
}Render Props Pattern and Usage
Classic Render Props Implementation:
class MouseTracker extends React.Component {
state = { x: 0, y: 0 };
handleMouseMove = (event) => {
this.setState({ x: event.clientX, y: event.clientY });
};
render() {
return (
<div onMouseMove={this.handleMouseMove}>
{this.props.render(this.state)}
</div>
);
}
}
// Usage
<MouseTracker render={({ x, y }) => (
<h1>Mouse position: {x}, {y}</h1>
)} />Function Component Implementation:
function MouseTracker({ render }) {
const [position, setPosition] = useState({ x: 0, y: 0 });
useEffect(() => {
const handleMouseMove = (e) => {
setPosition({ x: e.clientX, y: e.clientY });
};
document.addEventListener('mousemove', handleMouseMove);
return () => document.removeEventListener('mousemove', handleMouseMove);
}, []);
return render(position);
}HOC vs. Render Props Comparison
| Feature | HOC | Render Props |
|---|---|---|
| Code Organization | Horizontal composition (wraps component) | Vertical composition (nested rendering) |
| Readability | May cause “wrapper hell” | Clearer rendering flow |
| Learning Curve | Simpler | Requires understanding render prop concept |
| TypeScript Support | Needs complex type definitions | More direct type inference |
| Performance | May add component nesting | Renders target component directly |
Best Practices for Compositional Development
Mixed Usage Pattern:
// Enhance base component with HOCs
const EnhancedComponent = withLogging(withTheme(MyComponent));
// Use Render Props during rendering
<EnhancedComponent render={({ theme }) => (
<div style={{ background: theme.background }}>
{/* Content */}
</div>
)} />Modern Alternatives:
- Hooks: Replace most HOC and Render Props scenarios.
- Compound Components: Build complex UIs via component composition.
- Context API: Share global state.
Design Principles:
- Single Responsibility: Each HOC/Render Prop focuses on one function.
- Clear Interfaces: Define clear props and render callbacks.
- Avoid Over-Abstraction: Use advanced patterns only when necessary.
- Type Safety: Ensure type correctness with TypeScript.



