skip to Main Content

I’m not aware of any use case for using Context API if an app already uses a tool like Redux. Seems like Context API would only be useful for something quick and dirty where performance wasn’t critical and the developer didn’t know Redux. Does this seem like an accurate assertion? Ie if an app is already implementing Redux then there’s no additional use case which would justify the use of Context API?

2

Answers


  1. "Is there any use case to use context api if redux is already in place for an app?"

    Yes, there is/are. Context API is a mechanism used to share data (including state) between React Components. Redux is a State Management tool.

    You can have both Redux (for managing state) and Context sharing data (different from Redux state) between Components.

    Here’s a real life open source React app using both Redux and Context API at the same time.

    Recommended reading: Why React Context is Not a "State Management" Tool (and Why It Doesn’t Replace Redux)

    Login or Signup to reply.
  2. The Context API allows you to pass a value down from any component (anywhere in the tree) to all of its descendents. Redux manages a single global state. This is completely different.

    Here is a concrete example where you need the Context API even though you are using Redux: let’s say that you are designing a timeline-like page containing many Posts (each post having an id allowing you to look it up in the Redux store), and each Post component contains a lot of sub components, to show for instance the title, the content, the likes, the comments, the tags, etc.

    All of these sub components need access to the post id in order to get the right data from the Redux store. You could pass it directly from the parent Post component to all of the children (and grandchildren, etc), but this may get annoying, so rather than prop-drilling you can instead wrap each Post in a Context with the post id as a value, and then all of the children and grandchildren can use the context value directly without any prop-drilling.

    There is no way you can solve this problem with Redux, because it relies on having separate contexts for each post.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search