5

Build Decoupled React Components with Inversion of Control

 2 years ago
source link: https://blog.bitsrc.io/inversion-of-control-with-react-584533e49245
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Build Decoupled React Components with Inversion of Control

Imagine you’re implementing an e-commerce checkout, and the product manager has temporally chosen PayPal as payment provider. But it’s planned to change the provider for another one, e.g.: Stripe. Looking for small changes in the future, how would you implement this?

Inversion of Control (IoC) probably will help you in this case.

What is IoC?

IoC is a programming principle where you invert the control flow of a program, it’s used to decouple your code. You can read more about here, let’s go code.

You have the checkout.component.tsx that is responsible for creating the checkout flow. It renders the product list, total of payment and the payment form that is provided by PayPal.

The problem here is that your checkout flow knows about PayPal, and that can generate a huge refactor in the future.

To prevent this, you can use ElementType and interfaces.

ProviderProps ensure that any provider will implement the correct methods. ComponentProps forces the checkout flow to receive a provider and mount it, passing the given props.

Now we can create a “dumb” component that knows how to control the screen state, like loading and feedback.

And the responsible for managing the payment with PayPal can be isolated, totally decoupling the code.

Now, you can create a simple container that mount the checkout component and pass the correct props.

You can even create a factory method that returns the correct provider in a scenario you have more than one.

I hope that this article helped you to understand how to use inversion of control with react and how to decouple your code to be more maintainable.

Build with independent components, for speed and scale

Instead of building monolithic apps, build independent components first and compose them into features and applications. It makes development faster and helps teams build more consistent and scalable applications.

OSS Tools like Bit offer a great developer experience for building independent components and composing applications. Many teams start by building their Design Systems or Micro Frontends, through independent components. Give it a try →

0*UfYFvePAcsaZRYMZ?q=20
inversion-of-control-with-react-584533e49245
An independent product component: watch the auto-generated dependency graph

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK