javascript / expert
Snippet
Composable Logic via Higher-Order Hook Interceptors
Higher-order hooks allow you to wrap existing hooks to inject cross-cutting concerns like analytics, logging, or performance tracking without modifying the original hook's logic.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
const withAnalytics = (useHook: Function) => (args: any) => {const result = useHook(args);useEffect(() => {if (result.triggered) {Analytics.track('Action Performed', { ...args });}}, [result.triggered]);return result;};const useLoggedAuth = withAnalytics(useAuth);
react
Breakdown
1
const withAnalytics = (useHook) => (args) => ...
A factory function that returns a new hook, following the decorator pattern for hooks.
2
useEffect(() => { ... }, [result.triggered])
Intercepts internal hook state changes to perform secondary side-effects automatically.