React / 46
Single responsibility: one job per piece
Split big components by job, not by size. Data logic goes in hooks, calculations in plain functions, and components just show things.
One job, one reason to change
A handy test: describe what a component does. If you need the word "and", it probably has more than one job. "Fetches the menu and filters it and renders cards" is three jobs.
before · RestaurantMenu.jsx
One component, five jobs
- fetches the menu
- tracks loading and errors
- filters veg items
- renders the list
- renders each card
hooks/
useMenu()
utils/
filterVeg()
components/
MenuList · MenuCard
Split by job
Most React code falls into three kinds of pieces:
| Piece | Its job | Lives in |
|---|---|---|
| Custom hook | Data and state logic: fetching, subscriptions, timers | hooks/useMenu.js |
| Plain function | Calculations: filter, sort, format a price. Data in, data out, no React | utils/filterVeg.js |
| Component | Show things. Props in, JSX out | components/MenuList.jsx |
Each file is a small module: it exports one thing, imports what it needs, and can be read and tested on its own. That's what "modular code" means.
Before and after
import { useEffect, useState } from "react";
export function RestaurantMenu() {
const [items, setItems] = useState([]);
const [vegOnly, setVegOnly] = useState(false);
useEffect(() => {
fetch("https://dummyjson.com/recipes?limit=10")
.then((res) => res.json())
.then((data) => setItems(data.recipes));
}, []);
const shown = vegOnly
? items.filter((i) => i.tags.includes("Vegetarian"))
: items;
return (
<section>
<label>
<input type="checkbox" checked={vegOnly}
onChange={(e) => setVegOnly(e.target.checked)} /> Veg only
</label>
<ul>{shown.map((i) => <li key={i.id}>{i.name}</li>)}</ul>
</section>
);
}import { useState } from "react";
import { useMenu } from "../hooks/useMenu";
import { filterVeg } from "../utils/filterVeg";
import { MenuList } from "./MenuList";
export function RestaurantMenu() {
const items = useMenu(); // data: a custom hook
const [vegOnly, setVegOnly] = useState(false);
const shown = vegOnly ? filterVeg(items) : items; // logic: a plain function
return (
<section>
<label>
<input type="checkbox" checked={vegOnly}
onChange={(e) => setVegOnly(e.target.checked)} /> Veg only
</label>
<MenuList items={shown} /> {/* UI: a small component */}
</section>
);
}The "after" version reads like a summary: get the menu, maybe filter it, show it. filterVeg can be tested with a plain array, no React needed. useMenu can be reused on another page. You'll write hooks like useMenu in the next topic.
A common folder layout for this:
src/
components/ # UI pieces: MenuList.jsx, MenuCard.jsx
hooks/ # custom hooks: useMenu.js, useOnlineStatus.js
utils/ # plain functions: filterVeg.js, formatPrice.jsGotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
