Applying Design Patterns in React: Strategy Pattern

Read Time:2 Minute, 45 Second

This article is about a problem many of us encounter in React & Frontend development (sometimes even without realizing that it’s a problem): Having a piece of logic implemented throughout different components, hooks, utils, etc.

Let’s dive into the problem details and how to solve it. As the title suggests, we’re going to use the Strategy Pattern to solve it.

The problem: Shotgun Surgery

Shotgun Surgery is a code smell where making any modifications requires making many small changes to many different places.

Applying Design Patterns in React: Strategy Pattern
(image source: https://refactoring.guru/smells/shotgun-surgery)

How can this happen in a project? Let’s imagine we need to implement pricing cards for a product, and we adjust the price, the currency, the discount strategy and the messages based on where the client is coming from:

Pricing Cards

Most of us would probably implement the pricing card as follows:

  • Components: PricingCard, PricingHeader, PricingBody.
  • Utility functions: getDiscountMessage (in utils/discount.ts), formatPriceByCurrency (in utils/price.ts).
  • The PricingBody component also calculates the final price.

Here’s the full implementation:

Now let’s imagine we need to change the pricing plan for a country, or add a new pricing plan for another country. What will you have to do with the above implementation? You’ll have to at least modify 3 places and add more conditionals to the already messy if-else blocks:

  • Modify the PricingBody component.
  • Modify the getDiscountMessage function.
  • Modify the formatPriceByCurrency function.

If you’ve already heard of S.O.L.I.D, we’re already violating the first 2 principles: The Single Responsibility Principle & The Open-Closed Principle.

The solution: Strategy Pattern

The Strategy Pattern is quite straightforward. We can simply understand that each of our pricing plans for the countries is a strategy. And in that strategy class, we implement all the related logic for that strategy.

Suppose you are familiar with OOP, we can have an abstract class (PriceStrategy) that implements the shared/common logic, and then a strategy with different logic will inherit that abstract class. The PriceStrategy abstract class looks like this:

Enter fullscreen mode Exit fullscreen mode

And we simply pass the instantiated strategy as a prop to the PricingCard component:

Enter fullscreen mode Exit fullscreen mode

with the props of PricingCard defined as:

Enter fullscreen mode Exit fullscreen mode

Again, if you know OOP, not only we’re using Inheritance, but we’re also using Polymorphism here.

Here’s the full implementation of the solution:

And let us ask the same question again: How do we add a new pricing plan for a new country? With this solution, we simply need to add a new strategy class, and we don’t need to modify any of the existing code. By doing so, we’re satisfying S.O.L.I.D as well.

Conclusion

So, by detecting a code smell – Shotgun Surgery – in our React codebase, we have applied a design pattern – Strategy Pattern – to solve it. Our code structure went from this:

Before - Shotgun Surgery

to this:

After - Strategy Pattern

Now our logic lives in one place and is no longer spread throughout many places anymore.

If you’re interested in design patterns & architectures and how they can be used to solve problems in the Frontend world, make sure to give me a like & a follow.

Source: https://dev.to/itshugo/applying-design-patterns-in-react-strategy-pattern-enn

WP Ad Inserter plugin for WordPress

Tag Cloud

Java Java Logical Programs OTP Generation in Java python Recursion youtube video ASCII Upper and Lower Case blockchain javascript graph learn to code software development Successful Software Engineers breadth first search Java Array Programs Java Programs Uncategorized android ios programming kotlin web-development django data sql cybersecurity database swiftui serverless aws swift rust react background-position gradients loader mask grid nth-child pseudo elements indieweb WordPress Print Array without brackets C++ factorial Java String Programs Final Keyword Static Variable Axie Infinity Cryptokitties NFT games tool inserting MISC Tips Codes python code python projects python3 system info python project Bigginers How to Do Integrations Payment Gateways PHP checkout page in php Implement stripe payment gateway in Step by step in PHP integrate stripe gatway in php mysql payment gateway integration in php step by step payment gateway integration in php step by step with source code payment gateway integration in website PHP Integrate Stripe Payment Gateway Tutorial PHP shopping cart checkout code shopping cart in php stripe php checkout PHP/MySQL/JSON best international payment gateway does google pay accept international payments how to accept international payments in india paytm payment gateway razorpay codeigniter github razorpay custom checkout github razorpay get payment details razorpay integration in codeigniter github razorpay international payments Razorpay payment gateway integration in CodeIgniter razorpay payment gateway integration in php code Razorpay payment gateway integration with PHP and CodeIgniter Razorpay payment gateway setup in CodeIgniter Library & Frameworks Tips & Tricks UI/UX & Front-end coding birds online html code for google sign in login with google account in PHP login with google account using javascript login with google account using javascript codeigniter login with google account using php login with google account using php source code
Sentiment prediction with Python Previous post Sentiment prediction with Python
Top 5 API testing tools 2022 Next post Top 5 API testing tools 2022

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.