Dependency injection

Many of the modules/components that we write have dependencies. A proper management of these dependencies is critical for the success of the project. There is a technique (most people consider it a pattern) called dependency injection that helps solving the problem.

In React the need of dependency injector is easily visible. Let’s consider the following application tree:

  1. // Title.jsx
  2. export default function Title(props) {
  3. return <h1>{ props.title }</h1>;
  4. }
  5. // Header.jsx
  6. import Title from './Title.jsx';
  7. export default function Header() {
  8. return (
  9. <header>
  10. <Title />
  11. </header>
  12. );
  13. }
  14. // App.jsx
  15. import Header from './Header.jsx';
  16. class App extends React.Component {
  17. constructor(props) {
  18. super(props);
  19. this.state = { title: 'React in patterns' };
  20. }
  21. render() {
  22. return <Header />;
  23. }
  24. };

The string “React in patterns” should somehow reach the Title component. The direct way of doing this is to pass it from App to Header and then Header pass it down to Title. However, this may work for these three components but what happens if there are multiple properties and deeper nesting. Lots of components will act as proxy passing properties to their children.

We already saw how the higher-order component may be used to inject data. Let’s use the same technique to inject the title variable:

  1. // inject.jsx
  2. const title = 'React in patterns';
  3. export default function inject(Component) {
  4. return class Injector extends React.Component {
  5. render() {
  6. return (
  7. <Component
  8. {...this.props}
  9. title={ title }
  10. />
  11. )
  12. }
  13. };
  14. }
  15. // -----------------------------------
  16. // Header.jsx
  17. import inject from './inject.jsx';
  18. import Title from './Title.jsx';
  19. var EnhancedTitle = inject(Title);
  20. export default function Header() {
  21. return (
  22. <header>
  23. <EnhancedTitle />
  24. </header>
  25. );
  26. }

The title is hidden in a middle layer (higher-order component) where we pass it as a prop to the original Title component. That’s all nice but it solves only half of the problem. Now we don’t have to pass the title down the tree but how this data reaches the inject.jsx helper.

Using React’s context (prior v. 16.3)

In v16.3 React’s team introduced a new version of the context API and if you are going to use that version or above you’d probably skip this section.

React has the concept of context. The context is something that every React component has access to. It’s something like an event bus but for data. A single store which we access from everywhere.

  1. // a place where we will define the context
  2. var context = { title: 'React in patterns' };
  3. class App extends React.Component {
  4. getChildContext() {
  5. return context;
  6. }
  7. ...
  8. };
  9. App.childContextTypes = {
  10. title: React.PropTypes.string
  11. };
  12. // a place where we use the context
  13. class Inject extends React.Component {
  14. render() {
  15. var title = this.context.title;
  16. ...
  17. }
  18. }
  19. Inject.contextTypes = {
  20. title: React.PropTypes.string
  21. };

Notice that we have to specify the exact signature of the context object. With childContextTypes and contextTypes. If those are not specified then the context object will be empty. That can be a little bit frustrating because we may have lots of stuff to put there. That is why it is a good practice that our context is not just a plain object but it has an interface that allows us to store and retrieve data. For example:

  1. // dependencies.js
  2. export default {
  3. data: {},
  4. get(key) {
  5. return this.data[key];
  6. },
  7. register(key, value) {
  8. this.data[key] = value;
  9. }
  10. }

Then, if we go back to our example, the App component may look like that:

  1. import dependencies from './dependencies';
  2. dependencies.register('title', 'React in patterns');
  3. class App extends React.Component {
  4. getChildContext() {
  5. return dependencies;
  6. }
  7. render() {
  8. return <Header />;
  9. }
  10. };
  11. App.childContextTypes = {
  12. data: React.PropTypes.object,
  13. get: React.PropTypes.func,
  14. register: React.PropTypes.func
  15. };

And our Title component gets it’s data through the context:

  1. // Title.jsx
  2. export default class Title extends React.Component {
  3. render() {
  4. return <h1>{ this.context.get('title') }</h1>
  5. }
  6. }
  7. Title.contextTypes = {
  8. data: React.PropTypes.object,
  9. get: React.PropTypes.func,
  10. register: React.PropTypes.func
  11. };

Ideally we don’t want to specify the contextTypes every time when we need an access to the context. This detail may be wrapped again in a higher-order component. And even better, we may write an utility function that is more descriptive and helps us declare the exact wiring. I.e instead of accessing the context directly with this.context.get('title') we ask the higher-order component to get what we need and pass it as props to our component. For example:

  1. // Title.jsx
  2. import wire from './wire';
  3. function Title(props) {
  4. return <h1>{ props.title }</h1>;
  5. }
  6. export default wire(Title, ['title'], function resolve(title) {
  7. return { title };
  8. });

The wire function accepts a React component, then an array with all the needed dependencies (which are registered already) and then a function which I like to call mapper. It receives what is stored in the context as a raw data and returns an object which is later used as props for our component (Title). In this example we just pass what we get - a title string variable. However, in a real app this could be a collection of data stores, configuration or something else.

Here is how the wire function looks like:

  1. export default function wire(Component, dependencies, mapper) {
  2. class Inject extends React.Component {
  3. render() {
  4. var resolved = dependencies.map(
  5. this.context.get.bind(this.context)
  6. );
  7. var props = mapper(...resolved);
  8. return React.createElement(Component, props);
  9. }
  10. }
  11. Inject.contextTypes = {
  12. data: React.PropTypes.object,
  13. get: React.PropTypes.func,
  14. register: React.PropTypes.func
  15. };
  16. return Inject;
  17. };

Inject is a higher-order component that gets access to the context and retrieves all the items listed under dependencies array. The mapper is a function receiving the context data and transforms it to props for our component.

Using React’s context (v. 16.3 and above)

For years the context API was not really recommended by Facebook. They mentioned in the official docs that the API is not stable and may change. And that is exactly what happened. In the version 16.3 we got a new one which I think is more natural and easy to work with.

Let’s use the same example with the string that needs to reach a <Title> component.

We will start by defining a file that will contain our context initialization:

  1. // context.js
  2. import { createContext } from 'react';
  3. const Context = createContext({});
  4. export const Provider = Context.Provider;
  5. export const Consumer = Context.Consumer;

createContext returns an object that has .Provider and .Consumer properties. Those are actually valid React classes. The Provider accepts our context in the form of a value prop. The consumer is used to access the context and basically read data from it. And because they usually live in different files it is a good idea to create a single place for their initialization.

Let’s say that our App component is the root of our tree. At that place we have to pass the context.

  1. import { Provider } from './context';
  2. const context = { title: 'React In Patterns' };
  3. class App extends React.Component {
  4. render() {
  5. return (
  6. <Provider value={ context }>
  7. <Header />
  8. </Provider>
  9. );
  10. }
  11. };

The wrapped components and their children now share the same context. The <Title> component is the one that needs the title string so that is the place where we use the <Consumer>.

  1. import { Consumer } from './context';
  2. function Title() {
  3. return (
  4. <Consumer>{
  5. ({ title }) => <h1>Title: { title }</h1>
  6. }</Consumer>
  7. );
  8. }

Notice that the Consumer class uses the function as children (render prop) pattern to deliver the context.

The new API feels easier to understand and eliminates the boilerplate. It is still pretty new but looks promising. It opens a whole new range of possibilities.

Using the module system

If we don’t want to use the context there are a couple of other ways to achieve the injection. They are not exactly React specific but worth mentioning. One of them is using the module system.

As we know the typical module system in JavaScript has a caching mechanism. It’s nicely noted in the Node’s documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require(‘foo’) will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require(‘foo’) may not cause the module code to be executed multiple times. This is an important feature. With it, “partially done” objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

How is that helping for our injection? Well, if we export an object we are actually exporting a singleton and every other module that imports the file will get the same object. This allows us to register our dependencies and later fetch them in another file.

Let’s create a new file called di.jsx with the following content:

  1. var dependencies = {};
  2. export function register(key, dependency) {
  3. dependencies[key] = dependency;
  4. }
  5. export function fetch(key) {
  6. if (dependencies[key]) return dependencies[key];
  7. throw new Error(`"${ key } is not registered as dependency.`);
  8. }
  9. export function wire(Component, deps, mapper) {
  10. return class Injector extends React.Component {
  11. constructor(props) {
  12. super(props);
  13. this._resolvedDependencies = mapper(...deps.map(fetch));
  14. }
  15. render() {
  16. return (
  17. <Component
  18. {...this.state}
  19. {...this.props}
  20. {...this._resolvedDependencies}
  21. />
  22. );
  23. }
  24. };
  25. }

We’ll store the dependencies in dependencies global variable (it’s global for our module, not for the whole application). We then export two functions register and fetch that write and read entries. It looks a little bit like implementing setter and getter against a simple JavaScript object. Then we have the wire function that accepts our React component and returns a higher-order component. In the constructor of that component we are resolving the dependencies and later while rendering the original component we pass them as props. We follow the same pattern where we describe what we need (deps argument) and extract the needed props with a mapper function.

Having the di.jsx helper we are again able to register our dependencies at the entry point of our application (app.jsx) and inject them wherever (Title.jsx) we need.

  1. // app.jsx
  2. import Header from './Header.jsx';
  3. import { register } from './di.jsx';
  4. register('my-awesome-title', 'React in patterns');
  5. class App extends React.Component {
  6. render() {
  7. return <Header />;
  8. }
  9. };
  10. // -----------------------------------
  11. // Header.jsx
  12. import Title from './Title.jsx';
  13. export default function Header() {
  14. return (
  15. <header>
  16. <Title />
  17. </header>
  18. );
  19. }
  20. // -----------------------------------
  21. // Title.jsx
  22. import { wire } from './di.jsx';
  23. var Title = function(props) {
  24. return <h1>{ props.title }</h1>;
  25. };
  26. export default wire(
  27. Title,
  28. ['my-awesome-title'],
  29. title => ({ title })
  30. );

If we look at the Title.jsx file we’ll see that the actual component and the wiring may live in different files. That way the component and the mapper function become easily unit testable.

Final thoughts

Dependency injection is a tough problem. Especially in JavaScript. Lots of people didn’t realize that but putting a proper dependency management is a key process of every development cycle. JavaScript ecosystem offers different tools and we as developers should pick the one that fits in our needs.