Pattern Fundamentals Beginner
Separation of Concerns
Organizing code into separate layers for data, logic, presentation, and styling stops a change in one area from spreading into unrelated code.
The problem
You’ve probably opened a component file and found 500 lines of spaghetti, with API calls next to inline styles and business logic mixed into the JSX.
The pattern
I split code into layers, where each layer only deals with one kind of work, such as fetching data, applying business rules, rendering, or styling.
Problem
I’ve seen this pattern too many times. You might want to reuse a discount rule on another page, but it’s written in the middle of a component, next to the fetch call and the markup, so you end up copying and pasting it. To test the rule, you have to render the component and mock the API first.
When the kinds of work are mixed like this, one change in the backend can mean edits all over the UI. If a field in the API is renamed, you have to find each component that uses it. Your designer might be afraid to tweak the layout because they might break business logic they don’t understand.
Solution
API calls go in a service layer that returns plain objects the rest of the app can use. Business rules become pure functions that don’t depend on where the data comes from or how it’s displayed. Components only handle rendering: they get their data through props and call the handlers they’re given when the user does something. Styles go in their own files.
That way, you can change how data is fetched without touching your UI, and to test validation, you just call a function and check the result, without rendering anything in React.
Separation of concerns is about which kind of work goes in which layer of the app. Single Responsibility is about how much one function or component does. A component that renders a whole dashboard might be entirely in the presentation layer, but it does too much, and that’s a single responsibility problem.
This sounds like more work up front, and it is. But the first time you swap REST for GraphQL and only have to change the service layer, or a new developer finds their way around your codebase in a day instead of a week, you’ll be glad you did it.
Example
These examples take code that mixes several kinds of work and move each kind into its own layer.
Basic Layer Separation
This component does four kinds of work. It contains the API’s URL and field names, it applies a pricing rule, it renders markup, and it sets styles.
// ❌ MIXED: data, business rule, markup, and styles in one place
function ProductCard({ productId }) {
const [product, setProduct] = useState(null);
useEffect(() => {
fetch(`/api/products/${productId}`)
.then(r => r.json())
.then(setProduct);
}, [productId]);
if (!product) return <div>Loading...</div>;
const price = product.on_sale ? product.list_price * 0.8 : product.list_price;
return (
<div style={{ padding: '20px', border: '1px solid #ccc' }}>
<h2>{product.product_name}</h2>
<p>${price.toFixed(2)}</p>
</div>
);
}
In the separated version, each kind of work has its own piece of code. The last piece is a container component, which fetches the data and passes it to the component that renders it. Presentational vs. Container covers that split in detail.
// ✅ Data layer: the only code that contains the URL and the API's field names
const productApi = {
async fetchProduct(id) {
const data = await fetch(`/api/products/${id}`).then(r => r.json());
return { name: data.product_name, listPrice: data.list_price, onSale: data.on_sale };
}
};
// ✅ Business logic: a pure function with no fetch and no React
function finalPrice(product) {
return product.onSale ? product.listPrice * 0.8 : product.listPrice;
}
// ✅ Presentation: renders the props it's given, styled by a class
function ProductCard({ name, price }) {
return (
<div className="product-card">
<h2>{name}</h2>
<p>${price.toFixed(2)}</p>
</div>
);
}
// ✅ Container: connects the layers
function ProductCardContainer({ productId }) {
const [product, setProduct] = useState(null);
useEffect(() => {
productApi.fetchProduct(productId).then(setProduct);
}, [productId]);
if (!product) return <div>Loading...</div>;
return <ProductCard name={product.name} price={finalPrice(product)} />;
}
Now if list_price is renamed in the API, only productApi has to change. You can test the sale discount by calling finalPrice with a plain object, and the cart page can use the same function.
Separating Business Logic from Framework Code
A custom hook that contains the cart rules, like the first one below, is already separate from the markup, and for many apps that’s enough. Moving the rules into a plain class goes one step further, and it’s worth doing when the same rules have to run outside React, such as on the server, or when you want to test them without rendering anything.
// Works, but the cart rules can only run inside a React component
function useShoppingCart() {
const [items, setItems] = useState([]);
const addItem = (product) => {
setItems(prev => {
const existing = prev.find(item => item.id === product.id);
if (existing) {
return prev.map(item => item.id === product.id
? { ...item, quantity: item.quantity + 1 } : item);
}
return [...prev, { ...product, quantity: 1 }];
});
};
return { items, addItem };
}
// Business logic: a plain class that runs anywhere
class Cart {
constructor(items = []) { this.items = items; }
addItem(product) {
const existing = this.items.find(item => item.id === product.id);
if (existing) {
return new Cart(this.items.map(item => item.id === product.id
? { ...item, quantity: item.quantity + 1 } : item));
}
return new Cart([...this.items, { ...product, quantity: 1 }]);
}
getTotal() {
return this.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}
}
// Framework code: a thin hook that stores the cart in React state
function useShoppingCart() {
const [cart, setCart] = useState(() => new Cart());
return {
items: cart.items,
total: cart.getTotal(),
addItem: (product) => setCart(prev => prev.addItem(product))
};
}
// A test of the rules doesn't need React
expect(new Cart().addItem({ id: 1, price: 5 }).getTotal()).toBe(5);
Separating Styles from Component Logic
The styling layer is the easiest one to pull out. The inline style object moves into a CSS file, and the component only names a class, so a designer can change the colors without opening the component.
// ❌ MIXED: Styles embedded in component
function Button({ onClick, children }) {
return (
<button onClick={onClick}
style={{ padding: '10px 20px', backgroundColor: '#007bff', color: 'white' }}>
{children}
</button>
);
}
// ✅ SEPARATED: CSS module handles styling
import styles from './Button.module.css';
function Button({ onClick, children }) {
return <button onClick={onClick} className={styles.button}>{children}</button>;
}
/* Button.module.css */
.button { padding: 10px 20px; background-color: #007bff; color: white; }
.button:hover { background-color: #0056b3; }
Benefits
- I know what I’m looking at as soon as I open a file, because it handles one concern instead of mixing them all together.
- Testing gets simpler, because you can test validation by calling a function, without any rendering or mocking.
- A pure function such as a pricing calculation can be reused anywhere, from a React component to a Node script.
- You can update how data is fetched without touching components, and change styling without affecting business logic.
- Developers can work in parallel, with one handling the API integration while another builds the UI.
- Each code review can stay focused on one concern at a time.
Tradeoffs
- With more files, you spend more time moving between layers, and for simple features it can feel like overkill.
- Your team needs to agree on boundaries, or you’ll spend a lot of time arguing about what belongs where.
- Separation can conflict with colocation, because sometimes keeping related code together is clearer than spreading it across files just to keep the layers pure.
- Debugging gets trickier when a bug spans several layers.
- It’s hard to find the right amount of separation, because too little leaves tangled code, and too much leaves you with more abstraction than the code needs.
- You can’t separate everything perfectly, because what the UI needs affects which data you fetch, and the other way around.
- For prototypes, strict separation can slow you down.
- Container components that coordinate everything can keep growing until they’re doing too much themselves, which is the problem that Single Responsibility deals with.
Summary
With separation of concerns, you split code into layers for data fetching, business logic, presentation, and styling. Because each layer has its own job, a change in one layer doesn’t spread into the others, and developers can work on different layers at the same time. The amount of separation you need depends on the project. A quick prototype might not need separate layers at all, but a large app with several developers working on it usually does.