While there are still some pros and cons of using Redux vs Context API in React, there is no single advantage of using the legacy context API comparing to the new one. The main reason why is that there is no guarantee that the old API will be supported in React 17.x. 👋😢
As the docs provide the examples of using the API migrating to the new approach of coding seems to be an easy thing to do. But in the real world chances are that you are building and maintaining the library and it is more than the one component that needs to be updated. Furthermore updating the API requires developers to change both the context provider and the context consumer which may be impossible if you have only exposed the provider (for some reason 🤔). So it all made me think about the question…
Can we update our provider component without breaking the legacy API consumers?
I’m not quite sure if someone else will put a question this way but that’s how I started the little challenge this post is all about.
👨🏻💻 All right fellas, let’s start coding! The example below shows the legacy context API in action. We’ve created a
<Context /> component that passes the context to its children. It this particular example it is the
<Legacy /> component that receives the
This is what we’ll see as an output ⬇
Well done, we are using the legacy context API. Let’s rewrite the same example using the 🆕 API!
This is the output we gonna achieve ⬇️
Okay, well done 👏
Now let’s imagine that we have our library exporting just the
<Context /> component expecting our users to have an access to the context we set in it. If we upgrade the component and even export
const ExampleContext those people who were using it before won’t have any warning or crash going on 🚨. The consumers would just receive an empty
this.context and no data in it.
We do need compatibility! 🔌
To take care of our users we can create something that allows consuming the context both ways. This approach will let the old users still have the data in
this.context as it is in done in the
<Legacy /> component below. At the same time, developers could start using the new Context API (
<New />) making sure that it won’t be deprecated in the nearest future. Here is the code of this solution:
And the output is what we’ve expected ⇣
All right it’s up to you to decide whether you want to slightly reduce the amount of code to be thrown away while migrating or not 🤔 In some cases it’s worth to support the legacy API for a while to make sure that the users are comfortable in using the tools that you build.
The code repository for the medium post: