"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Stop abuse React Context API

Stop abuse React Context API

Published on 2024-08-14
Browse:504

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!

Release Statement This article is reproduced at: https://dev.to/peteryuan/stop-abuse-react-context-api-5dp?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3