Build Decoupled React Components with Inversion of Control
Inversion of control in React: a typed provider contract, a dumb checkout and a factory, so swapping PayPal for Stripe never touches the checkout.

On this page
Imagine you’re implementing an e-commerce checkout, and the product manager has temporarily chosen PayPal as the payment provider. The plan is to switch to another one later, Stripe for example. If you want that future change to be small, how would you implement this?
Inversion of Control (IoC) will probably help you here.
What is inversion of control?
IoC is a programming principle where you invert the control flow of a program, and it’s used to decouple your code. You can read more about it here. Instead of a component deciding which dependency it uses and calling it, the dependency is handed to the component from the outside. In React, the simplest way to hand something over is a prop, so what follows is dependency injection through props: no container library, no decorators. Let’s go to the code.
Why a checkout that knows about PayPal is a problem
You have checkout.component.tsx, which is responsible for the checkout flow. It renders the product list, the payment total, and the payment form provided by PayPal.
checkout.component.tsx
const CheckoutComponent = ({ products }: { products: Product[] }) => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const total = useMemo(
() => products.reduce((sum, product) => sum + product.price, 0),
[products]
);
const onPayError = () => { /* ... */ };
const onPaySuccess = () => { /* ... */ };
const onPay = () => {
paypal.someMethod(onPaySuccess, onPayError);
};
// All the payment stuff goes here
return (
<div>
<div>
Products:
<ul>
{products.map(product => <li key={product.id}>{product.name} - U${product.price}</li>)}
</ul>
<p>Total: U${total}</p>
</div>
<PaypalForm />
</div>
);
};tsxThe problem is that your checkout flow knows about PayPal, and that can lead to a huge refactor in the future.
Define a contract every payment provider must implement
To prevent this, you can use component types and interfaces.
checkout.types.ts
import type { ComponentType } from 'react';
export interface Product {
id: string;
name: string;
price: number;
}
export interface ProviderProps {
amount: number;
onPaymentStart: () => void;
onPaymentSucceed: () => void;
onPaymentError: (error: string) => void;
// any other prop every provider needs goes here
}
export interface CheckoutProps {
products: Product[];
provider: ComponentType<ProviderProps>;
}tsProviderProps ensures that any provider implements the correct callbacks and receives what it needs to charge, the amount. CheckoutProps forces the checkout flow to receive a provider and mount it, passing those props.
Two naming details that matter more than they look. I call it CheckoutProps and not ComponentProps, because React already exports a ComponentProps type and you don’t want two of them in the same file. And the contract speaks the checkout’s language (onPaymentSucceed), not PayPal’s (onApprove) or Stripe’s (confirmPayment). The moment a vendor’s vocabulary leaks into the contract, the contract is just the vendor with extra steps.
Make the checkout a “dumb” component
Now we can create a “dumb” component that only knows how to control the screen state, like loading and feedback.
decoupled-checkout.component.tsx
import { useMemo, useState } from 'react';
import type { CheckoutProps } from './checkout.types';
export const CheckoutComponent = ({ products, provider: Provider }: CheckoutProps) => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const total = useMemo(
() => products.reduce((sum, product) => sum + product.price, 0),
[products]
);
const onPaymentStart = () => {
setError('');
setLoading(true);
};
const onPaymentSucceed = () => redirectToHome();
const onPaymentError = (message: string) => {
setLoading(false);
setError(message);
};
return (
<div>
<div>
Products:
<ul>
{products.map(product => <li key={product.id}>{product.name} - U${product.price}</li>)}
</ul>
<p>Total: U${total}</p>
</div>
{loading && <p>Processing payment...</p>}
{error && <p role="alert">{error}</p>}
<Provider
amount={total}
onPaymentStart={onPaymentStart}
onPaymentSucceed={onPaymentSucceed}
onPaymentError={onPaymentError}
/>
</div>
);
};tsxNotice the destructuring provider: Provider. JSX treats a lowercase tag as an HTML element, so <provider /> would render an unknown <provider> tag. Renaming it to Provider is what makes React mount it as a component.
Isolate the PayPal integration in its own provider
The code responsible for handling the payment with PayPal can now be isolated, fully decoupled from the checkout.
paypal-provider.component.tsx
import type { FormEvent } from 'react';
import type { ProviderProps } from './checkout.types';
export const PayPalProvider = ({ amount, onPaymentStart, onPaymentSucceed, onPaymentError }: ProviderProps) => {
const handlePayment = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
onPaymentStart();
paypal.someMethod(amount)
.then(() => {
onPaymentSucceed();
})
.catch((error: unknown) => {
onPaymentError(error instanceof Error ? error.message : 'Payment failed');
});
};
return (
<form onSubmit={handlePayment}>
<PayPalForm />
<button type="submit">Pay</button>
</form>
);
};tsxThe event.preventDefault() is not decoration: without it, submitting the form reloads the page and your payment flow dies halfway. And whatever PayPal throws, the checkout only ever receives a string, because that’s what the contract promised.
Wire the provider in a container
Now you can create a simple container that mounts the checkout component and passes the correct props.
checkout.container.tsx
import { CheckoutComponent } from './decoupled-checkout.component';
import { PayPalProvider } from './paypal-provider.component';
export const CheckoutContainer = () => {
const products = useCartProducts();
return <CheckoutComponent products={products} provider={PayPalProvider} />;
};tsxPass the component itself (PayPalProvider), not an element (<PayPalProvider />). The checkout is the one that decides when to mount it and with which callbacks.
Choose between several providers with a factory
If you have more than one provider, you can even create a factory method that returns the correct one.
provider-factory.ts
import type { ComponentType } from 'react';
import type { ProviderProps } from './checkout.types';
import { PayPalProvider } from './paypal-provider.component';
import { StripeProvider } from './stripe-provider.component';
export enum PaymentProvider {
PAYPAL = 'PAYPAL',
STRIPE = 'STRIPE'
}
export const getSelectedProvider = (): PaymentProvider =>
PaymentProvider.PAYPAL; // in real life: a feature flag, config, the user's country...
export const getProviderContainer = (provider: PaymentProvider): ComponentType<ProviderProps> => {
switch (provider) {
case PaymentProvider.PAYPAL:
return PayPalProvider;
case PaymentProvider.STRIPE:
return StripeProvider;
}
};tscheckout.container.tsx
import { CheckoutComponent } from './decoupled-checkout.component';
import { getProviderContainer, getSelectedProvider } from './provider-factory';
export const CheckoutContainer = () => {
const products = useCartProducts();
const provider = getProviderContainer(getSelectedProvider());
return <CheckoutComponent products={products} provider={provider} />;
};tsxI named the enum PaymentProvider so it doesn’t fight with the Provider the checkout renders, and the factory stays in a .ts file with no JSX. Because the switch covers every member of the enum, TypeScript knows the function always returns; add a third provider to the enum and forget the case, and the build fails instead of the checkout.
One gotcha: the factory returns components defined once, at module level. Never build the provider inline, like provider={(props) => <PayPalProvider {...props} />} inside a render. That’s a new component type on every render, so React remounts the provider each time and the payment form loses whatever state it had.
When inversion of control is overkill
I like this pattern, but I don’t put it everywhere. An abstraction costs one more file, one more indirection and a contract you have to keep honest. Before reaching for it, I ask a few questions:
- Is there a real second implementation? “We might switch providers someday” with no date and no candidate is usually not enough. If PayPal is the only provider for the foreseeable future, a well-isolated
PayPalFormcomponent is cheaper, and you can extract the contract the day Stripe shows up. With one implementation you are guessing what the contract should be; with two you know. - Do the vendors actually fit the same shape? PayPal’s React SDK wants a
PayPalScriptProvideraround its buttons, Stripe’s wants anElementsprovider around its form, and the flows themselves differ (popups, redirects, 3D Secure). A small contract likeProviderPropsholds up fine, because each provider hides that mess inside itself. If you find yourself addingisPayPalflags to the contract, the abstraction is leaking and it’s time to rethink it, not to add more props. - Is it a leaf component? A button, an input or a tooltip doesn’t need injected dependencies. IoC pays off at the boundary with something you don’t own: payments, analytics, maps, auth.
If the answer to the first question is no, don’t feel bad about the “coupled” version. Coupling to a decision you are not going to change is just code.
I hope this article helped you understand how to use inversion of control with React to decouple your code and keep it maintainable.
Key takeaways
- A component that calls a third-party SDK directly couples your product flow to that vendor; changing vendors becomes a refactor.
- Define the contract (
ProviderProps) once: every payment provider implements the same start, success and error callbacks. - Keep the checkout “dumb”: it receives a provider component, mounts it and only manages screen state such as loading and errors.
- Each vendor integration lives in its own provider component, and a container or factory decides which one to mount. Pass the component, defined at module level, never an inline one.
- Name the contract in your product’s language (
CheckoutProps,onPaymentSucceed), not the vendor’s, and don’t reuse names React already exports. - Skip IoC when there is no real second implementation, when vendors don’t fit one shape, or for leaf components. Extract the contract the day the second provider arrives.