Will adding redundant React Context Provider affect performance

Viewed 93

in my app, we have 2 context providers let say contextA and contextB, and we allow user to set the value for each context. And we have 2 options to do this.

1. We just wrap all children in 2 context provider, if user doesnt set either provider, it fallback to its default value. Some example code like this:

   const ConfigProvider: FC<PropsWithChildren<ConfigProviderProps>> = props => {
       const { children, a, b } = props;

   return <ConfigContextA.Provider value={{ ...defaultContextA, ...a }}>
      <ConfigContextB.Provider {...defaultContextB, ...b}>{children}</ConfigContextB.Provider>
    </ConfigContextA.Provider>
   }

2. We write if-else branch to only wrap the provider if user passed as props:

   const ConfigProvider: FC<PropsWithChildren<ConfigProviderProps>> = props => {
       const { children, a, b } = props;

   if(a&b)
   {return <ConfigContextA.Provider value={{ ...defaultContextA, ...a }}>
      <ConfigContextB.Provider {...defaultContextB, ...b}>{children}</ConfigContextB.Provider>
    </ConfigContextA.Provider>}

    if(a) {return <ConfigContextA.Provider value={{ ...defaultContextA, ...a }}>
     {children}
    </ConfigContextA.Provider>}

    if(b) {return <ConfigContextB.Provider value={{ ...defaultContextB, ...b }}>
     {children}
    </ConfigContextB.Provider>}
   
   }
    return <>{children}</>}

If we follow option 1, then the code will much cleaner, there is no if-else logic, however, every children may be wrapped with unnecessary context.

If we follow option 2, children only be wrapped with corresponding provider, however the apps need to run additional if-else branching logic.

Note that the context value is rarely be re-configured on runtime ( some value like locale)

So my question is between these 2 options, which one is better in performance and memory cost? thanks

0 Answers
Related