1.1 KiB
1.1 KiB
TypeScript/React Best Practices
Component Structure
- Use functional components with hooks
- Keep components small and focused (< 200 lines)
- Extract custom hooks for reusable logic
- Use TypeScript interfaces for props
// GOOD: Typed props with clear interface
interface UserCardProps {
user: User;
onSelect: (id: string) => void;
}
const UserCard: React.FC<UserCardProps> = ({ user, onSelect }) => {
return (
<div onClick={() => onSelect(user.id)}>
{user.name}
</div>
);
};
State Management
- Use
useStatefor local state - Use
useReducerfor complex state logic - Lift state up only when needed
- Consider context for deeply nested prop drilling
Performance
- Use
React.memofor expensive pure components - Use
useMemoanduseCallbackappropriately (not everywhere) - Avoid inline object/function creation in render when passed as props
Security
- Never use
dangerouslySetInnerHTMLwith user input - Sanitize URLs before using in
hreforsrc - Validate props at component boundaries