Is it a good idea to use React.Context to inject UI-Components?

Viewed 222

I plan to build a react component library. The react components are UI-Components but should only implement a specific logic. I want the user to be able to define a set of atoms (basic react components) that are used to compose the actual components. My main goal is to make the library independent of a specific UI-Component-Library like MaterialUI, ChakraUI, etc.

My idea was to use a React.Context to inject the components like this:

// Button Atom
const Button: FC = ({ children }) => (<button>{children}</button>)

const atoms = { button: Button }
const AtomContext = createContext(atoms);

// "higher" component
const HigherComponent: FC = () => {
  const atoms = useContext(AtomContext)
  // Logic ...

  return (
    <atoms.button>click me</atoms.button>
  )
}

export default function App() {
  return (
    <AtomContext.Provider value={atoms}>
      <HigherComponent />
    </AtomContext.Provider>
  );
}

This solves my problem. But I'm not sure if it is a good idea. Are there better ways to inject UI-dependencies? What may be problems with my approach?

2 Answers

This is a question that can result in multiple answers based on personal experience.

But overall the idea to pass component trough context is a bit of misuse of that concept.

Also it does not bring much benefit from making a standalone library that can be imported via package.json or making a folder with components and importing them.

If you need to pass some specific things to your components you can have a custom provider as you did there, but as far as the component themselves, there is no common sense to use context.

If you end goal is to shorten the list of imports of component with custom context hook and just getting them like that, I think that is a bad tradeoff overall.

I just read this article about using react context for dependency injection. The authors opinion is, that react context for injecting non-react dependencies into components is good practice. However, I'm not sure if that applies to injecting a specific set of react components. Since, react components are nothing more than functions I think it should be alright to use reacts context for that.

Related