Dependency injection in React

<p>React Components should not contain business logic, do you agree? If yes, keep reading. If not, stop now. This article is for someone else.</p> <h2>TL; DR;</h2> <p>Add the dependency injection to your React project in 3 steps:</p> <ul> <li>create a &ldquo;container&rdquo; to put your dependency in</li> <li>create a hook&nbsp;<code>useInject</code>&nbsp;to retrieve the dependency</li> <li>use the hook in the Components</li> </ul> <h2>Long version</h2> <p>If you&rsquo;re on the fence about the answer, I&rsquo;ll try to give you some insights into why we shouldn&rsquo;t do this:</p> <ul> <li>React is a library for creating user interfaces; this definition should discourage us from putting business logic in Components.</li> <li>Components containing business logic are challenging to read, maintain, and test.</li> <li>Extracting business logic from Components is an excellent idea to be able to reuse it.</li> </ul> <p>Okay, so if we take the business logic out of the Components, we should write it somewhere, such as in external classes or functions. How do we do that? By using dependency injection!</p> <h2>What is the Dependency Injection, and why should you use it</h2> <p>Dependency Injection (DI) is a software design pattern that separates the creation of objects from their use. In practice, instead of creating the things within the code that uses them, the instantiation of the objects is delegated to an external entity responsible for creating the objects and providing them to the components that need them.</p> <p><a href="https://itnext.io/dependency-injection-in-react-6fa51488509f"><strong>Read More</strong></a></p>