Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection with React Hooks

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.

like image 438
SteevieP Avatar asked May 14 '20 12:05

SteevieP


1 Answers

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} />;
};
like image 91
Jeshken Avatar answered Oct 16 '22 18:10

Jeshken