1.2 KiB
1.2 KiB
JavaScript/React Best Practices
Component Structure
- Use functional components with hooks
- Keep components small and focused (< 200 lines)
- Extract custom hooks for reusable logic
- Use PropTypes for runtime type checking
// GOOD: Clear component with PropTypes
import PropTypes from 'prop-types';
const UserCard = ({ user, onSelect }) => {
return (
<div onClick={() => onSelect(user.id)}>
{user.name}
</div>
);
};
UserCard.propTypes = {
user: PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
}).isRequired,
onSelect: PropTypes.func.isRequired,
};
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 - Avoid inline object/function creation in render
Security
- Never use
dangerouslySetInnerHTMLwith user input - Sanitize URLs before using in
hreforsrc - Validate props at component boundaries