Home Web Front-end JS Tutorial Modular React architecture

Modular React architecture

Nov 09, 2024 pm 07:29 PM

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 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
Copy after login
Copy after login

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>
      }
    />
  )
}




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

<p>At just under 400 lines, this button is trivially simple. Even if the popover is<br>
another 500 lines of spaghetti. Does "cleaning" it up or splitting it up really<br>
benefit us, or our users, in any way? It depends. If this is all we'll need for<br>
this button, who cares. Let's move on!</p>
<p>But two months have passed and a PM and designer from another product team love<br>
your button and want it in their app's header. They have a <em>simple</em> list, no<br>
pressure from their end, of some changes they'd like you to accommodate and if<br>
you could please give an ETA by end of day for LT that'd be great, thanks:</p>

<ul>
<li>Update the button's styling and display text based on the app it's shown in</li>
<li>Show a completely different set of popovers, per app</li>
<li>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</li>
</ul>

<p>Can Jimbo cram all of this new functionality into the same components?<br><br>
Yes. Will splitting or refactoring benefit the users or impress your managers?<br><br>
No. But refactoring has some strong arguments at this level of complexity:</p>

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


<h3>
  
  
  The modular architecture approach
</h3>

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

<ul>
<li>KISS, DRY, & other acronym blankets</li>
<li>Separation of concerns</li>
<li>Atomicity! Decoupling! Onomatopoeia!</li>
</ul>

<p>These are great, and help inform Jimbo's next attempt. He didn't get PIPed after<br>
all, and actually got a promo for delivering ahead of schedule and for sharing<br>
so many meetings and documents.<br><br>
But he's wiser now and learned a cool way to implement those adages. It looks<br>
something like this:<br>
</p>

<div class="code" style="position:relative; padding:0px; margin:0px;"><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">/v-bucks-button
├── button.tsx
├── index.ts
└── /v-bucks-popover
│ ├── popover.tsx
Copy after login
Copy after login

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:

/v-bucks-button
├── button.tsx
├── index.ts
└── /v-bucks-popover
│ ├── popover.tsx
Copy after login
Copy after login
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>
      }
    />
  )
}
Copy after login
/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
Copy after login

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

The above is the detailed content of Modular React architecture. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

How do I install JavaScript? How do I install JavaScript? Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

See all articles