CodeBlanks Logo Icon CodeBlanks

Dependency injection

Learn dependency injection.

Dependency injection

Dependency injection (DI) means a component receives its dependencies from outside. The component does not call new UserService() itself; the userService is supplied via a prop or constructor.

This way the component depends on an interface, not a concrete class. In tests a mock is supplied; in production the real service. On the React side, DI is done with Context.

DI with React

In React, DI is usually done with Context. A RepoContext is created; the real or mock repository is given to the Provider. Components get the repository via useContext.

In tests, the Provider receives a mock repository; the component works with the mock without knowing. This makes unit tests easy; no real network is needed.

Practice Create RepoContext

Create a RepoContext. Use createContext, with default value null. Export the result. Import createContext from React.

Starter code

App.js
import React from 'react';

// Import createContext from react
// Create RepoContext

export default RepoContext;

Sample solution

App.js
import React, { createContext } from 'react';

const RepoContext = createContext(null);

export default RepoContext;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the DI-supplied thing called?

Question
What a component receives from outside through DI is called a ____.
Answer
What a component receives from outside through DI is called a dependency.

Explanation: The outside-supplied thing is a dependency.

2 Match the DI pieces

Term Meaning
Context Dependency carrier
Provider Supplies the value
useContext Reads the value
Mock Test value

3 Which mechanism does DI use in React?

  • With StyleSheet Correct answer
  • With useEffect
  • Context and Provider
  • With FlatList

Explanation: Context + Provider carries the dependency.

All lessons in Expert