@scaffold-ai/react-service-provider
Version:
React context-based service provider for dependency injection.
87 lines (56 loc) • 2.11 kB
Markdown
# Service Provider
A React component library for **dependency injection** in your app.
It provides a simple, React-friendly way to inject and consume services throughout your component tree.
---
## What is a Service?
A **Service** is any object encapsulating logic separate from your UI — for example:
- Communicating with your backend API
- Wrapping third-party hooks or libraries
- Managing global state or utilities
---
## How to Use
### 1. Define a Service Contract (Interface)
Define the interface your app depends on.
By coding against an interface, you can swap implementations without changing your app’s code.
```typescript
import { Service } from "./Service";
interface ApiService extends Service {
getRequest(endpoint: string): string;
useHook: () => void; // You can even inject hooks!
}
namespace ApiService {
export const id = Symbol.for("ApiService");
}
export default ApiService;
```
### 2. Create a Concrete Service Implementation
Implement the interface for a specific environment or use case.
```typescript
import ApiService from "./ApiService";
export default class ApiServiceDev implements ApiService {
serviceId = ApiService.id;
getRequest(endpoint: string): string {
return `You hit ${endpoint}`;
}
useHook = () => useYourHook();
}
```
### 3. Inject Services in Your App
Create a list of service instances (usually in a `services/index.ts`), then provide them to your app using the `ServiceProvider`.
```tsx
import ApiServiceDev from "./services/ApiServiceDev";
import { ServiceProvider } from "./index";
const services = [new ApiServiceDev()];
const App = () => (
<ServiceProvider value={services}>{/* ...your app */}</ServiceProvider>
);
```
### 4. Consume Services with `useService`
Use the `useService` hook to access any injected service by its ID.
```tsx
import { useService } from "./index";
const Component = () => {
const { getRequest } = useService<ApiService>(ApiService.id);
return <div>{getRequest("some/endpoint")}</div>;
};
```