Managing constants like API endpoints, user messages, and theme colors in a React project can quickly become messy if not structured properly. In this guide, we’ll walk through best practices for organizing these constants in a scalable and maintainable way.
API Routes: Centralizing your API endpoints makes your codebase cleaner and easier to maintain.
//src/constants/apiRoutes.js
export const API_BASE = "https://api.example.com";
export const API_ROUTES = {
auth: {
login: `${API_BASE}/auth/login`,
register: `${API_BASE}/auth/register`,
logout: `${API_BASE}/auth/logout`,
},
products: {
list: `${API_BASE}/products`,
detail: id => `${API_BASE}/products/${id}`,
create: `${API_BASE}/products/create`,
},
users: {
profile: id => `${API_BASE}/users/${id}/profile`,
update: id => `${API_BASE}/users/${id}/update`,
}
};
Benefits:
- Easy to update base URLs
- Clear separation of concerns
- Reusable across services and components
Messages: Instead of hardcoding messages in components, define them in a centralized file. This is especially useful for localization and consistent UX.
//src/constants/messages.js
export const MESSAGES = {
success: {
login: "Login successful!",
save: "Data saved successfully.",
},
error: {
network: "Network error. Please try again.",
unauthorized: "You are not authorized to perform this action.",
required: field => `${field} is required.`,
},
info: {
loading: "Loading data...",
noData: "No data available.",
}
};
Benefits:
- Easier to manage and translate
- Consistent tone across the app
- Reusable in alerts, toasts, modals, etc.
Theme Colors: Define your color palette in one place to ensure visual consistency and simplify theme changes.
//src/constants/colors.js
export const COLORS = {
primary: "#007bff",
secondary: "#6c757d",
success: "#28a745",
danger: "#dc3545",
warning: "#ffc107",
info: "#17a2b8",
light: "#f8f9fa",
dark: "#343a40",
background: "#ffffff",
text: "#212529"
};
Benefits:
- Consistent styling across components
- Easy to integrate with CSS-in-JS or Tailwind config
- Simplifies dark/light theme switching
How to Use Constants:
In any component or service, simply import what you need:
- import { API_ROUTES } from '../constants/apiRoutes';
- import { MESSAGES } from '../constants/messages';
- import { COLORS } from '../constants/colors';
Seyed Hamed Vahedi
Tue, 4 November, 2025