score:13

Accepted answer

React Context is used to store state and share it across multiple components. It is especially useful when you have a deep tree of components and do not want to pass down state as props across multiple levels of components. Contexts in React consist of a Provider (where you set the value of the context) and a Consumer (where you get the value).

React Hooks provide a useContext Hook, which is another way to access context values. useContext replaces the Consumer component.

Redux is a state management library. It does a lot more than simply storing state with a set/get interface as Contexts do. Internally, Redux actually uses React Context to store its state. However, it additionally forces you to change state via actions. This makes sense if your state changes are complex (e.g. a single action should change multiple parts of your state). In a complex application, Redux can prevent bugs and inconsistent state.

As a rule of thumb, you should use React Context as long as your state changes are simple. If you run into problems where it is hard to keep multiple parts of your state in sync, it might make sense to consider Redux.

Whether you want to use Context Consumers or Hooks is totally up to you and a matter of taste. The advantage of using Hooks is that you can consume multiple contexts more easily without having a deep component tree.

Context Consumers:

   <AuthenticationContext.Consumer>
       {user => (
           <LanguageContext.Consumer>
               {language => (
                   <StatusContext.Consumer>
                       {status => (
                           ...
                       )}
                   </StatusContext.Consumer>
               )}
           </LanguageContext.Consumer>
       )}
    </AuthenticationContext.Consumer>

useContext Hooks:

const user = useContext(AuthenticationContext)
const language = useContext(LanguageContext)
const status = useContext(StatusContext)

As for the Providers, they are the same whether you use Hooks or not.


Related Query

More Query from same tag