React Dependency Injection

The definition of Dependency Injection in software programming is:

Dependency injection is a programming technique in which an object or function receives other objects or functions that it requires, as opposed to creating them internally.

// Direct Coupling of dependency and MyApplication APP public class MyApplication { // coupling private EmailService email = new EmailService(); public void processMessages(String msg, String rec){} } // Simple way of implementing DI public class MyApplication { private EmailService email = null; // Now the Dependency is Injected in the constructor public MyApplication(EmailService svc){ this.email=svc; } public void processMessages(String msg, String rec){} }
// This is an example of Coupled Dependecny import getData from "..";

Some Alternatives

// import getData from ".."; Delete this const MySuperCOmponent = ({getData, ...}) => {}

Dependency Injection Via Context

import { getCustomListData } from "../hooks/getListData"; import { DIType } from "from ViewA"; import { DEFAULT_DI_CONTAINER } from "from ViewA"; const CUSTOM_DI_CONTAINER = { registry: { // this makes sure we get all the default functionality and override or add new ones ...DEFAULT_DI_CONTAINER.registry, getListData: getCustomListData, }, resolve() { return this.registry; }, };
import { AppDIProvider } from "from ViewA"; import Lists from "from ViewA"; import { CUSTOM_DI_CONTAINER } from "./di-container/custom-container"; const ViewB = () => { return ( <AppDIProvider container={CUSTOM_DI_CONTAINER}> <h2>This is a Custom Container Example</h2> <Lists /> </AppDIProvider> ); }; export default ViewB;

Local Development