Home > database >  React: Would it a better choice to use redux than context to pass a value from child to parent and s
React: Would it a better choice to use redux than context to pass a value from child to parent and s

Time:08-20

My react app structures like this (simplified)

<App> --> 
    need UserId information to conditional render something
    return (
     <Header/>
     <Contents/>
)
<Header> -->
   const login = () => retrieves an UserId after user login
   return (
      <Navbar etc/>
)
<Content> --> requires UserId information to do something

After user login in <Header> component, I need to pass it back to <App> as well as share it with <Content> component and others.

As my react app has more than five sibling components which all need access to userId information, I think it might not be a wise choice pass the information one by one using props. Would it be better to use Redux here because as far as I read, Context is for passing from parent to child not vice versa?

CodePudding user response:

You can use both Context and Redux to share data across components in react without using props.

There are 2 main things to consider when you choose between.

  1. Redux updates states faster than Context

    If you need to access your states quickly, or if your states change too rapid, then it is more convenient to use Redux.

  2. When you have too many Contexts you will have to manage different contexts across your app i.e. wrap different components with different contexts or wrap same component with too many contexts(I call it context hamburger, when the number of contexts grow it might get messy).

You can use both at the same time. There is no problem with that. For login information, Context is used more often, since you only login and logout once in a while.

  • Related