0 day streak
javascript / expert
Snippet

Dependency Injection via Context for Decoupled Services

Implementing Dependency Injection (DI) allows you to decouple component logic from specific service implementations. This makes it trivial to swap a real API service for a mock during unit testing or local development.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
const ApiContext = createContext<ApiService | null>(null);
export const useService = () => {
const service = useContext(ApiContext);
if (!service) throw new Error('Service not provided');
return service;
};
const App = ({ serviceImplementation }: { serviceImplementation: ApiService }) => (
<ApiContext.Provider value={serviceImplementation}>
<Dashboard />
</ApiContext.Provider>
);
react
Breakdown
1
createContext<ApiService | null>(null)
Creates a container for the dependency that can be fulfilled at the root level.
2
if (!service) throw new Error(...)
A safety check to ensure components are always wrapped in the appropriate provider, improving debugging.