Hook Composition vs Function Composition
What you'll learn: The fundamental difference between composing hooks (which manage React state and effects) versus composing plain functions (which just transform data).
The Core Distinction
When you compose hooks, you're combining pieces of React's stateful logic — each hook call registers with React's internal system, tracking state, effects, and their lifecycles. When you compose plain functions, you're simply chaining pure transformations that don't interact with React at all.
Think of it like this: Hook composition is like connecting electrical appliances — each one plugs into the power grid (React's system) and maintains its own state. Function composition is like passing ingredients through a recipe — each step transforms what it receives, but nothing persists or "plugs in" anywhere.
Hook Composition Example
function useUserData(userId) {
// This hook composes useState + useEffect
const [user, setUser] = useState(null);
useEffect(() => {
fetchUser(userId).then(setUser);
}, [userId]);
return user;
}
Each hook call (useState, useEffect) registers with React's rendering system.
Function Composition Example
function formatUser(user) {
// Just data transformation, no React involvement
return {
displayName: `${user.firstName} ${user.lastName}`,
avatar: user.avatarUrl || '/default.png'
};
}
This is a pure function. It doesn't call hooks or track anything.
Why It Matters
You can mix them! Your custom hook can call other hooks (hook composition) AND use utility functions (function composition):
function useFormattedUser(userId) {
const user = useUserData(userId); // Hook composition
return user ? formatUser(user) : null; // Function composition
}
Key Takeaway: Hook composition builds stateful React logic by combining multiple hook calls; function composition transforms data without touching React's system — and you'll often use both together in custom hooks.