Dependency injection and service location are interesting concepts that are not limited to React development. To really understand them, let's move away from components for a while. For a moment, imagine that we wanted to create a sitemap. To do this, we could perhaps use code resembling the following code:
let backend = { getAll() { // ...return pages } }; class SitemapFormatter { format(items) { // ...generate xml from items } } function createSitemap() { const pages = backend.getAll(); const formatter = new SitemapFormatter(); return formatter.format( pages.filter(page => page.isPublic) ); } let sitemap = createSitemap();
In this example, createSitemap
has two dependencies. Firstly, we fetch pages from backend
. This is a kind of global storage object. We used something similar to this when we looked at the Flux architecture.
The second dependency is to the SitemapFormatter
implementation...