β»οΈ Reusability Principles in React
Reusability is a core principle of React that encourages breaking your UI into smaller, manageable, and reusable components to reduce duplication and increase maintainability.
π 1. DRY β Donβt Repeat Yourself
- Avoid duplicating UI logic across components
- Extract repeated JSX into reusable components or hooks
- Use shared utility functions for repeated business logic
π¦ 2. Component Abstraction
Break UI into smaller, self-contained components:
// Reusable Button component
function Button({ children, onClick }) {
return (
<button onClick={onClick} className="bg-blue-600 text-white px-4 py-2 rounded">
{children}
</button>
);
}
π£ 3. Reusable Hooks
Encapsulate logic in custom hooks to avoid repetition:
import { useState, useEffect } from 'react';
function useFetch(url) {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url).then(res => res.json()).then(setData);
}, [url]);
return data;
}
ποΈ 4. Props for Configurability
Design components to accept props for flexible reuse:
function Alert({ type, message }) {
const bg = type === 'error' ? 'bg-red-500' : 'bg-green-500';
return <div className={`text-white p-3 rounded ${bg}`}>{message}</div>;
}
π§± 5. Composition Over Inheritance
React encourages composing components with children instead of extending them.
function Card({ children }) {
return <div className="shadow p-4 rounded">{children}</div>;
}
π 6. Organize Code by Feature
- Keep related components, hooks, and styles together
- Helps isolate concerns and maximize reuse
β Summary
- Break down UI into small, testable units
- Design generic, prop-driven components
- Extract repeated logic into hooks
- Favor composition over complexity