Search code examples
javascriptreactjsdesign-patternsreact-contextanti-patterns

React Context: Nested re-use/enhancement (anti-pattern?)


I would like to know if it is an anti-pattern to create nested context providers (the same context) and progressively extend the data. So, using the current context and enriching/overriding it from that point downward.

Are there obvious (not to me yet) disadvantages to this approach ?

Is there relevant terminology for this that i might be missing, in order to search for more info ?

Why

I am building a sort of ABAC system for a product. This access can be affected by different items which are available for a specific item.

Approach

const AuthContext = React.createContext({});

const AuthContextProvider = ({ children, value }) => {
  const parentAuth = React.useContext(AuthContext);
  const updatedAuth = { ...parentAuth, ...value };

  return (
    <AuthContext.Provider value={updatedAuth}>{children}</AuthContext.Provider>
  );
};

And my usage would be something like

<AuthContextProvider value={{ user }}>
  <SomeConsumingComponent permission="RE_ORDER" />
...    
  <AuthContextProvider value={{ question: question1 }}>
    <SomeConsumingComponent permission="EDIT_TEXT" />
  </AuthContextProvider>
....
  <AuthContextProvider value={{ question:question2 }}>
    <SomeConsumingComponent permission="MODIFY_MEDIA" />
  </AuthContextProvider>
</AuthContextProvider>

Of course the consuming components can appear in quite more complex structures and i want to add the relevant "extra" data at the higher available point.


Solution

  • It looks like that they're testing exactly the scenario you're describing here:

    https://github.com/facebook/react/blob/2bf4805e4bd63dab45cd7f5e1ad32ef8fed3f6ab/packages/react-reconciler/src/__tests__/ReactNewContext-test.js#L277-L331

    Notice that they're consuming the context in the Provider and mutating the value (line 286).

    Since they expect these kind of usages, I don't see any reason why this would be an anti-pattern.