Track 04 · Lesson 10 of 15Code that stays easy to change

Track 04 · Code that stays easy to change

KISS: Keep it simple

Lesson 10 of 15· 5 min

Choose the plainest solution that solves the actual problem.

Follow one click

Toggle the sidebar in both versions

  1. onClick
  2. bus.emit()
  3. bus listener
  4. dispatch(TOGGLE)
  5. reducer
  6. context value
  7. useSidebarState()
  8. <Sidebar> renders

7

Hops from click to sidebar

5

Files to read to follow it

Seven hops across five files. Each hop is a place for a bug to hide, like a listener that subscribes twice.

5 files for one booleanWithout it
// sidebar-events.ts
export const bus = new EventEmitter<{ "sidebar:toggle": void }>();

// SidebarProvider.tsx
type Action = { type: "TOGGLE" } | { type: "SET"; open: boolean };

function reducer(state: { open: boolean }, action: Action) {
  switch (action.type) {
    case "TOGGLE": return { open: !state.open };
    case "SET": return { open: action.open };
  }
}

export function SidebarProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(reducer, { open: false });
  useEffect(() => bus.on("sidebar:toggle", () => dispatch({ type: "TOGGLE" })), []);
  return <SidebarContext.Provider value={state}>{children}</SidebarContext.Provider>;
}

// useSidebarState.ts
export const useSidebarState = () => useContext(SidebarContext).open;

// MenuButton.tsx
<Button onClick={() => bus.emit("sidebar:toggle")}>Menu</Button>

Count the hops#

Every step between cause and effect is somewhere a bug can hide and somewhere a reader has to look. The clever version takes seven hops across five files to open a sidebar. The simple one takes two, in one file you can read top to bottom.

Clever code usually comes from good intentions: "we might need other things to toggle the sidebar", "this is how big apps do it". But the tools that make large apps manageable, like event buses, global stores and dependency injection, are overhead in a small one.

Simple isn't the same as easy#

Simple means few moving parts. Sometimes that takes more thought than the clever version: finding the one useState that replaces a whole architecture is real design work.

Check yourself

A toggle works through an event bus, a reducer and a context. What's the main cost?