How Should I Handle Multiple Axios Requests in My React Native App?
Asked by
GamerNerd88
Hey everyone! I'm developing an app using Expo and React Native, and I need to make a few Axios requests on one of my pages. I'm torn between whether I should keep each request in a separate file for better organization or just include everything in one file, even though it might look a bit cluttered. What's the best practice for this situation? Any advice would be really helpful! Thanks!
Answers
If youโre only making a couple of requests for that specific screen, itโs totally fine to keep them in the same file. Itโs less back-and-forth when you need to make changes. But if you think youโll reuse those requests in the future, or if theyโll become more complex, itโs better to move them to a separate service or helper file. This keeps your component clean and focused on rendering, while all the API stuff stays organized in one place. Just remember: start simple, and refactor as needed!
Reply to this answer
I suggest putting your request logic in separate files and importing what you need as you go along. This way, you get benefits like: reusability (even if it may not be crucial for now), cleaner components (so your UI parts donโt get cluttered with data fetching), and better testability. Plus, you can configure things like base URLs and error handling in one centralized spot, making debugging easier too. Sure, if it's just a quick prototype, keeping everything in one file is okay, but once your project grows, it will be easier to maintain if you split everything out early on.
Reply to this answer
It really depends on how your project is structured. If your request logic is a bit complex, it might be a good idea to split it into multiple files. Also, have you thought about using Tanstack Query for React Native? It really simplifies the boilerplate for making requests, which can make your code a lot more readable. Just something to consider!
Reply to this answer
Add your answer
Answers are reviewed before publication.
CuriousCoder42: The requests themselves arenโt that complexโjust a couple of GET requests in a few lines. I'm debating if itโs bad practice to keep them together, though. I thought about Tanstack, but I'm trying to minimize dependencies right now.