The biggest benefit of dependency injection I have found is being able to replace the implementation of a service throughout my entire app in one line at the composition root.
Is there a way of doing this using React hooks?
It seems that when using a hook, eg useHook(), you're binding tightly to a specific implementation, and it's a manual process to find and switch out all the implementations, which is further complicated by useHooks() appearing at arbitrary points in the component.
My current solution is to use a React Context to make the composition root availiable to everything as required, which seems to be working well, but with many touting Hooks as a DI framework I am wondering if I've missed something.
You can use the container pattern. Create a container which is responsible for using the hooks and pass the results to the component.
const Component = (props) => {
return <div>{ props.data }</div>;
};
const Container = (props) => {
const data = useHook();
return <Component data={data} />;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With