Skip to content
ClapelloNotes by Barath
ReactCh 09 · 1/6
Beginner4 min readUpdated

React / 46

Single responsibility: one job per piece

TL;DR

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
split by responsibility

hooks/

useMenu()

fetching, loading and error state

utils/

filterVeg()

a pure function: data in, data out

components/

MenuList · MenuCard

UI only: props in, JSX out
Split by job, not by size. Data logic goes in a hook, pure calculations in a plain function, and the component is left with one job: showing things.

Split by job

Most React code falls into three kinds of pieces:

PieceIts jobLives in
Custom hookData and state logic: fetching, subscriptions, timershooks/useMenu.js
Plain functionCalculations: filter, sort, format a price. Data in, data out, no Reactutils/filterVeg.js
ComponentShow things. Props in, JSX outcomponents/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

RestaurantMenu.jsx
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>
  );
}
RestaurantMenu.jsx
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.js

Gotchas

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.