Search code examples
reactjsreduxreact-context

Why use react.useContext if you are using redux? What are the technical differences?


Why use react.useContext if you are already using redux? I am trying hard to understand what benefit react.useContext offers over redux. Is there something I am missing?

I am trying to deeper understand react.useContext and redux. So please explain why one is technically more suited for certain situation than the other. What are the technical differences?


Solution

  • Context and Redux do two different things.

    Context is a mechanism to pass a single, seldom-changing variable down the tree. Whenever that variable is changed, all consumers rerender, so it is best used to pass down things like a Theme, or a WebSocket connection used in many components. It's more useful for dependency injection.

    Redux on the other hand is made for managing plain objects (e.g. a WebSocket wouldn't go in here) holding data and subscribing efficiently to granular changes within that data.

    So it is likely you will use Context and a state mgmt library (there are also alternatives like MobX, Recoil, XState, Jotai, Zustand or Valtio) side-by-side, for different purposes. For more information, you can for example read this article.