Re-use a component that includes a context

I have a complex component that uses a context internally. For example:

// ComplexComponent.tsx

const MyContext = createContext({});
export function useMyContext() {
  return useContext(MyContext);
}

export default function ComplexComponent({ fooValue }) {
  return (
    <MyContext.Provider value={{ foo: fooValue }}>
      <NestedComponent />
    </MyContext.Provider>
  );
}
// NestedComponent.tsx

import { useMyContext } from './ComplexComponent';

export default function NestedComponent() {
  const { foo } = useMyContext();
  return (
    <div>
      { foo }
    </div>
  );
}

Is there a way to generate context(s) dynamically, so that I can re-use this component in other places in the code (while a few instances occur simultaneously)?

Obviously I’d have to put the createContext function inside ComplexComponent, but then I won’t be able to import useMyContext.

Answer

As React’s context is global, I didn’t want to even go in the direction of generating contexts dynamically.

I ended up using a simple state inside ComplexComponent, as it’s well encapsulated and allow using as many independent instances of ComplexComponent as I want.

However, this solution has the obvious downside of passing the “context params” down each level of children components.

Leave a Reply

Your email address will not be published. Required fields are marked *