Modular React architecture

On modular architecture

What’s modular architecture? Let’s go through an example of what it isn’t, and
we’ll work towards transforming it. By the end you may be convinced of its
merits or that it’s a colossal waste of time.

This is a real s…


This content originally appeared on DEV Community and was authored by Michael Mazzone

On modular architecture

What's modular architecture? Let's go through an example of what it isn't, and
we'll work towards transforming it. By the end you may be convinced of its
merits or that it's a colossal waste of time.

This is a real scenario I growth-mindsetted through at work. Names and details
anonymized, but a real-world example of a common concept should be fun to walk
through, if nothing else.

Requirements, and how to find them

Our site has a button that lives in the site header. It displays how many
V-Bucks the user has left, but also has some business logic baked into it:

  • If this is their first time visiting the site, open a popover to welcome them & show something they can do with their V-Bucks
  • If they have < 5 V-Bucks remaining, show a popover upselling more
  • If they are a Basic user, show one style of button; if SuperDuper user, show another, fancier button

And so on. There are many such cases our product managers and project managers
and design managers and Group V-Bucks Directors have dreamed up that we need to
handle.

Jimbo the intern has been tasked with implementing this because it's just a
button!

He sifts through fifteen conflicting iterations of Figma designs. He finds
requirements in as many separate Word docs as there are PMs. He organizes and
endures seven knowledge transfer sessions with seven teams to uncover the
ancient, proprietary knowledge of which services will provide the data he needs
for user type and V-Bucks count. The content team has reassured him that the
final version of all the strings will be approved by legal and marketing by end
of week, and with that, he's ready to build this button.

The hacker approach

Here's the first iteration of his V-Bucks button, popovers, and relevant
business logic.

Jimbo is pleased with the simple directory structure he's come up with:

/v-bucks-button
├── button.tsx
├── index.ts
└── /v-bucks-popover
│ ├── popover.tsx

So he starts building this button, and it begins innocently enough.

export const VBucksButton: React.FC<VBBProps> = ({ ... }) => {
  // Set up state
  const authConfig    = { ... }
  const { user }      = useAuth({ ...authConfig })
  const { vBucks }    = useGetVBucks({ user })
  const { telemetry } = useTelemetry()
  const { t }         = useTranslation('vBucksButton.content')
  const styles        = useButtonStyles()

  // Derive some state via business logic
  const handleClick = () => { ... }
  const buttonText  = vBucks === ERROR ? '--' : vBucks.toString();
  // About 25 more lines of various button state, error handling,
  // conditional rendering, with comments throughout explaining
  // why we're showing or hiding something or other

  const popoverProps = {
    // About 200 lines of typical popover handling,
    // telemetry, business logic, content to display, etc
  }

  const tooltipProps = {
    // Another 100 lines of the same for tooltip
  }

  return (
    <VBucksPopover
      {...popoverProps}
      trigger={
        <Tooltip {...tooltipProps}>
          <button
            ariaLabel={t('ariaLabel')}
            className={`
              about seven-hundred classnames for responsive design,
              accessibility, conditional premium styles, et cetera`}
            onClick={handleClick}>
            {buttonText}
          </button>
        </Tooltip>
      }
    />
  )
}

He's implemented a first go at it. The VBucksPopover has similarly complex
business logic, error handling, state management, styling, and comments excusing
tech debt in the name of shipping.

At just under 400 lines, this button is trivially simple. Even if the popover is
another 500 lines of spaghetti. Does "cleaning" it up or splitting it up really
benefit us, or our users, in any way? It depends. If this is all we'll need for
this button, who cares. Let's move on!

But two months have passed and a PM and designer from another product team love
your button and want it in their app's header. They have a simple list, no
pressure from their end, of some changes they'd like you to accommodate and if
you could please give an ETA by end of day for LT that'd be great, thanks:

  • Update the button's styling and display text based on the app it's shown in
  • Show a completely different set of popovers, per app
  • Open a new company-wide, standard upsell modal when the user's out of V-Bucks, but only in some regions, and only to users age 16+, and only if they're in experiment group A

Can Jimbo cram all of this new functionality into the same components?

Yes. Will splitting or refactoring benefit the users or impress your managers?

No. But refactoring has some strong arguments at this level of complexity:

  • Dev sanity
  • The sanity of the dev who replaces Jimbo when he's PIPed for not refactoring
  • More reps, so you do better from the start next time
  • Something to blog about later

The modular architecture approach

The morals of the Clean Code initiates, and other anal types who know enough to
answer on Stack Overflow regularly, and even your grandparents, look something
like this:

  • KISS, DRY, & other acronym blankets
  • Separation of concerns
  • Atomicity! Decoupling! Onomatopoeia!

These are great, and help inform Jimbo's next attempt. He didn't get PIPed after
all, and actually got a promo for delivering ahead of schedule and for sharing
so many meetings and documents.

But he's wiser now and learned a cool way to implement those adages. It looks
something like this:

/vBucksButton
├── /hooks
│ ├── index.ts
│ └── useButtonState.hook.ts
├── /vBucksPopover
│ ├── /app1Popover
│ │ ├── /hooks
│ │ │ ├── index.ts
│ │ │ └── usePopoverState.hook.ts
│ │ ├── ...
│ ├── /app2Popover
│ ├── index.ts
│ ├── popover.renderer.tsx
│ ├── popover.styles.ts
│ ├── popover.tsx
│ └── popover.types.ts
├── /utils
│ ├── experimentation.util.ts
│ ├── store.util.ts
│ ├── telemetry.util.ts
│ └── vBucks.businessLogic.util.ts
├── button.renderer.tsx
├── button.styles.ts
├── button.tsx
├── button.types.ts
└── index.ts

Looks like tons of boilerplate for a button and popover. Why would this be
better?

It depends. Here's Jimbo's brief overview with rationale:

  • Split each component into a container and renderer
  • Move state and business logic into hooks
  • The container uses hooks and passes along any props to the renderer
  • The renderer is concerned only with rendering what it's provided
  • Common functionality, business logic, or constants can live in utils
  • Separate files for types; they tend to be imported in multiple files and become circular deps that you need to extract anyways
  • Extracted TailwindCSS -- more on this below

It's infinitely scalable! These building blocks aren't broken down by
arbitrary rules like lines of code or "complexity". They're broken down by
purpose: each conceptual boundary serves a single purpose.

A PM wants you to make 10 new popovers? No problem -- Jimbo's architecture can
handle it.

Leadership wants better metrics on sales in some apps, but other teams don't
have the funding to build out telemetry to support this. Great! We have
telemetry utils that we can horizontally scale to meet various, changing
requirements.

A sweeping redesign means every single popover needs to display different stuff,
based on different conditions. It's typically much simpler now that all of the
stuff we render, and all the logic we use to render it, exist in well-defined
blocks. They're no longer commingled in a giant pile of conflict and logic
chains 20 lines long.

Here's a sample of this container / renderer pattern:

export const VBucksButton: React.FC<ContainerProps> = ({ ... }) => {
  // State comes from hooks
  const buttonProps = useButtonState()

  return (
    <VBucksPopover
      trigger={<VBucksButtonRenderer {...buttonProps} />}
    />
  )
}
export const VBucksButtonRenderer: React.FC<RendererProps> = ({ ... }) => {(
  <Tooltip {...tooltipProps}>
    <button
      ariaLabel{t('ariaLabel')}
      className={styles.vBucksButton}
      onClick={handleClick}>
      {buttonText}
    </button>
  </Tooltip>
)}
/* button.styles.ts */
.vBucksButton {
  @apply all-those same styles-go;
  @apply md:here md:to-make-it-manageable;
  @apply lg:as-these-grow-ever-larger;
}

Aside: The TailwindCSS docs explicitly recommend against using @apply to extract common classes like this. This causes almost zero difference in bundle size, and no other difference than that aside from "you have to come up with class names." Production-grade CSS almost always ends up being dozens of lines long, multiplied by however many elements need styling in a given component. This tradeoff seems worth it 90% of the time.

And the rest of the existing, and new, business logic lives in hooks & utils!

This new architecture satisfies the zealots and makes things easier to scale or
delete or move around.

Writing unit tests becomes less painful because you've got well-defined
boundaries. Your renderer no longer needs to mock ten different services to
validate that it shows some set of shinies given some input. Your hooks can
test, in isolation, that they match your intended business logic.

Did your entire state layer just change? It'd be a shame if the code in your
hook was tightly coupled with the code that uses it, but now it's a simpler
change and your renderer is still just expecting some input.

Final thoughts

This modular architecture adds a lot of boilerplate and can ultimately provide
zero benefit.

I can't practically recommend it if you're working on a passion project or
prioritize shipping & providing value above all. If you've got something that
seems like it might expand in scope over time, or that you may want to
completely overhaul after a POC, it can reduce tech debt... sometimes.

You can use tools like Plop to generate this boilerplate.

So what did I really learn from Jimbo's work & modular architecture?

Clean Code and acronyms we learn in school and the Well Ackshuallys of the world
are one end of a spectrum. Hacking together functional spaghetti code is another
end, and often works quite well, because ultimately all code is tech debt.

The best solution exists in some quantum state or combination of these ends, and
the path we choose will likely be decided based on:

  • How much we care about the thing we're building
  • How frequently management is asking for updates and ETAs
  • Reading something like this and one approach happens to bubble up into your consciousness when you build your next thing
  • Frustration, pain
  • The spaghetti becomes such a perf bottleneck that you're forced to rewrite it
  • The boilerplate becomes so draining that you cut corners


This content originally appeared on DEV Community and was authored by Michael Mazzone


Print Share Comment Cite Upload Translate Updates
APA

Michael Mazzone | Sciencx (2024-11-09T02:07:10+00:00) Modular React architecture. Retrieved from https://www.scien.cx/2024/11/09/modular-react-architecture/

MLA
" » Modular React architecture." Michael Mazzone | Sciencx - Saturday November 9, 2024, https://www.scien.cx/2024/11/09/modular-react-architecture/
HARVARD
Michael Mazzone | Sciencx Saturday November 9, 2024 » Modular React architecture., viewed ,<https://www.scien.cx/2024/11/09/modular-react-architecture/>
VANCOUVER
Michael Mazzone | Sciencx - » Modular React architecture. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/11/09/modular-react-architecture/
CHICAGO
" » Modular React architecture." Michael Mazzone | Sciencx - Accessed . https://www.scien.cx/2024/11/09/modular-react-architecture/
IEEE
" » Modular React architecture." Michael Mazzone | Sciencx [Online]. Available: https://www.scien.cx/2024/11/09/modular-react-architecture/. [Accessed: ]
rf:citation
» Modular React architecture | Michael Mazzone | Sciencx | https://www.scien.cx/2024/11/09/modular-react-architecture/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.