I'm diving into React for the first time, and honestly, it's a big shift from my Object-Oriented Programming background. I'm finding it challenging to understand concepts such as Dependency Injection (DI). Since functional programming doesn't utilize classes or interfaces (except when using TypeScript), what alternatives exist for DI?
Additionally, I would really appreciate any recommendations for solid online resources that explain JavaScript from an OOP perspective and share best practices. I'm trying to build an app, and it's turning into a bit of a mess!
1 Answer
When you're working with React, try to let go of that OOP mindset! Think of React components like functions that take in props and spit out HTML. You can think of state management through something called reducers, which handle data updates very cleanly. If you give them the same inputs, they always give you the same outputs, which helps keep things predictable, especially in larger apps.
For your question about DI, you can place dependencies directly into your app's context at the top level. This way, any component can access those dependencies without passing them through every layer of components. You can keep a singleton that provides necessary functions and update state as needed.

Oh right! I forgot to mention that DI can be handled using React's Context API! You can create a context that holds your functions and any data, and then just pull them as needed in your components.