Stop abuse React Context API

Several days ago I was adjusted to a new department. My new coworker gave me a task to refactor an existing React project.

When I was reading the code, I was shocked by the way of using the Context API. The coder before, who put everything (yes, almost everything) into a Context object, treated it as a store to manage all the states and even some local temp state. That’s insane!

And he also codes everything for a page in just one (yes, absolutely only one) component in one .ts file. It’s so hard for me to make it clear in my mind about the code’s logic. But I still accept these shitty code (I have no choice), so I make a big decision: I would rewrite all these pages in one week with Mobx and split the code into different functional components.

With Mobx, I create several stores to handle all data from the APIs and split one huge component into different small pieces; everything starts to become clear and simple. Local state should be in its scope where it would be used, the common part will be got from the store of Mobx.

Finally I totally removed the Context object, thousands of lines of code were removed, and the world is quiet again!

I want to say something about Context API. If you really have something, such as some global config information to share to the entire app, you can use Context API, But if you just want to avoid using some third-party state management library, that’s a bad idea to treat context as a replacement.

Let Context be Context and let state be managed by libraries like Mobx.

Stop abuse React Context API, please!


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top