Dependency Injection in React

Dependency Injection is a popular pattern implemented in many frameworks and libraries. At first glance React doesn't seem to have it, is that true?

Dependency Injection is a popular pattern implemented in many frameworks and libraries. At first glance React doesn’t seem to have it. But React actually supports built-in dependency injection through JSX, and you’re probably using it already. 😂

Dependency Injection in short

Dependency Injection solves a common problem: “hardcoded dependencies” - meaning the dependencies are fixed in the code. When an object A depends on an object B and then creates a second object, the dependency can’t be changed (because it’s been hardcoded).

For example, the Calculator class creates a logger service, hardcoded as ConsoleLogger, which can’t be changed later:

import ConsoleLogger from "./ConsoleLogger";

class Calculator {
  constructor() {
    this.logger = new ConsoleLogger();
  }

  add(a, b) {
    this.logger.log(`Adding ${a} to ${b}`);
    return a + b;
  }
}

However, when testing this class, developers want to “mock” the logger service (to stop logging to the console, for example). Or in production, they want to use SysLogger or another logger like Sentry’s (a SaaS logger), and they can’t, because the dependency is hardcoded.

We can fix this with a single commit using Dependency Injection like this:

-import ConsoleLogger from './ConsoleLogger';

class Calculator {
-   constructor() {
-       this.logger = new ConsoleLogger();
-   }
+   constructor(logger) {
+       this.logger = logger;
+   }

    add(a, b) {
        this.logger.log(`Adding ${a} to ${b}`);
        return a+b;
    }
}

Now the dependency no longer depends on object A creating object B:

const logger = new ConsoleLogger();
const calculator = new Calculator(logger);
const result = calculator.add(1, 2); // console shows "Adding 1 to 2"

And so developers can easily swap the dependency later:

const logger = new NullLogger();
const calculator = new Calculator(logger);
const result = calculator.add(1, 2); // console shows nothing

Thanks to Dependency Injection, the code ends up cleaner and more clearly modularized. Angular has a built-in Dependency Injection Container, and so do Symfony and Spring. But it seems React.js doesn’t?

JSX supports Dependency Injection

React supports Dependency Injection without needing a dependency injection container (like Angular), thanks to JSX.

Look at the component that renders product reviews in a table below:

Here’s the code that renders the table:

const ReviewList = props => (
  <List resource="reviews" perPage={50} {...props}>
    <Datagrid rowClick="edit">
      <DateField source="date" />
      <CustomerField source="customer_id" />
      <ProductField source="product_id" />
      <RatingField source="rating" />
      <TextField source="body" label="Comment" />
      <StatusField source="status" />
    </Datagrid>
  </List>
);

The component fetches data from the /review/ route of a REST API and passes in an extra parameter, perPage. But doesn’t render the reviews table itself. Instead, it leaves the rendering to its child component: . That means depends on for rendering, a parent-child relationship is created here, and that is Dependency Injection.

And like any other form of Dependency Injection, we can swap the “dependency” very easily. For example, in the case above, if we want to change the rendering to a “simple list” instead of a “data grid”, we just replace the child of with another component:

import { List, Datagrid, TextField, DateField } from 'react-admin';

const PostList = props => (
    <List resource="posts" perPage={50}>
        <SimpleList
            primaryText={review => <ItemTitle record={review} />}
            secondaryText={review => review.body}
        >
    </List>
)

React even lets you inject more than one dependency into an element. First, because an element can have more than one child. In the previous example, takes a list of the columns to display:

const ReviewList = props => (
  <List resource="reviews" perPage={50}>
    <Datagrid rowClick="edit">
      <DateField source="date" />
      <CustomerField source="customer_id" />
      <ProductField source="product_id" />
      <RatingField source="rating" />
      <TextField source="body" label="Comment" />
      <StatusField source="status" />
    </Datagrid>
  </List>
);

Besides injecting through child components, we can also inject through props. Below, we can inject a different DataGrid body:

const ReviewList = props => (
    <List resource="reviews" perPage={50}>
-       <Datagrid rowClick="edit">
+       <Datagrid rowClick="edit" body={<MyDatagridBody />} >
            <DateField source="date" />
            <CustomerField source="customer_id" />
            <ProductField source="product_id" />
            <RatingField source="rating" />
            <TextField source="body" label="Comment"/>
            <StatusField source="status" />
        </Datagrid>
    </List>
)

And since every dependency is a component, we can also inject dependencies into dependencies, like this:

const ReviewList = props => (
    <List resource="reviews" perPage={50}>
        <Datagrid
            rowClick="edit"
-           body={<MyDatagridBody />}
+           body={<MyDatagridBody withBulkActions />}
        >
            <DateField source="date" />
            <CustomerField source="customer_id" />
            <ProductField source="product_id" />
            <RatingField source="rating" />
            <TextField source="body" label="Comment"/>
            <StatusField source="status" />
        </Datagrid>
    </List>
)

So JSX has the basic features of a Dependency Injection Container: it lets you move, swap and configure dependencies flexibly.

React Context

Above we saw JSX used to implement Dependency Injection in JSX templates, so what about service functions? React encourages using components for services too. For example, we can pass a translation service through component props:

const englishTranslator = message => {
  if (message == "hello.world") {
    return "Hello, World!";
  }
  return "Not yet translated";
};

const Greeting = ({ translate }) => {
  return <div>{translate("hello.world")}.</div>;
};

const App = () => <Greeting translate={englishTranslator} />;

However, this can get clunky with a lot of code and nested layers. So React provides another way to declare Dependency Injection: context:

import React, { useContext } from "react";

const englishMessages = message => {
  if (message == "hello.world") {
    return "Hello, World!";
  }
  return "Not yet translated";
};

const TranslationContext = React.createContext();

const Greeting = () => {
  const translate = useContext(TranslationContext);
  return <div>{translate("hello.world")}.</div>;
};

const App = () => (
  <TranslationContext.Provider value={englishMessages}>
    <Greeting />
  </TranslationContext.Provider>
);

Wrapping up

Why doesn’t React provide a Dependency Injection Container like Angular? Simply because it’s not needed. JSX and context are already more than enough to make React apps modular and testable.

This is a strength of React: even for large-scale apps, React handles everything well without needing big, bulky frameworks (like Angular 😂):

References