2

In React, it's common for libraries, and app-internal utilities, to used context-based dependency injection. Some examples:

function MyComponent() {
  const client = useApolloClient(); // Apollo
  const store = useStore(); // React-Redux
  const { me, logout } = useContext(AuthContext); // utilities
  // etc..
}

I wonder, has anybody seen serious (or any for that matter) usage of the same technique for dependency injection of UI components? Would/could it solve any particular problem out there?

function MyComponent() {
  const { Button, TabBar, Header, NavList } = useContext(UIContext);
  // etc.
}

Some thoughts:

  • I've once written a hook that returns a component definition (instead of just some jsx), because I wanted to dynamically generate some component dynamically depending on state, but also to be able to render multiple of them.

  • In the typical theme use-case, I imagine it would just be a bit of an inversion of control, where instead of "consuming and applying the theme", you would be "letting the theme itself deal with it"

    // consuming/applying theme from context
    const { colors } = useTheme();
    return <button style={{ color: colors.primary }}>hello</button>;
    
    // let the
    const { Button } = useThemedComponents();
    return <Button>hello</Button>;
    

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.