jeudi 27 mai 2021

Nested re-use/enhancement of react context (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.

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=>
  <SomeConsumingComponent permission="RE_ORDER" />
...    
  <AuthContextProvider value=>
    <SomeConsumingComponent permission="EDIT_TEXT" />
  </AuthContextProvider>
....
  <AuthContextProvider value=>
    <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.


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 ?

Aucun commentaire:

Enregistrer un commentaire