Advanced Patterns for API Management in Large-Scale React Applications

Rate this content
Bookmark

In this talk, you will discover how to manage async operations and request cancellation implementing a maintainable and scalable API layer and enhancing it with de-coupled cancellation logic. You will also learn how to handle different API states in a clean and flexible manner.

This talk has been presented at React Advanced 2021, check out the latest edition of this React Conference.

FAQ

The instructor is Tomasz Fienli, a full-stack web and mobile developer with nine years of programming experience.

The course covers managing API requests in React using an API layer, handling different API states, creating custom hooks, canceling requests with Axios and an API layer, and using React query.

An API layer abstracts API calls into a single place, improving maintainability, scalability, flexibility, and code reusability. It allows for easier changes to the HTTP client and keeps the API-related code centralized.

The four API states are Idle, Pending, Success, and Error.

You can enhance the API layer with abort logic, using a cancel token from Axios to cancel ongoing requests as needed.

The API layer keeps all API-related code in one place, making it easier to maintain and scale by adding new API methods and files without changing the components.

The API layer can be used with React Query by importing API methods and using React Query hooks like useQuery. It keeps the implementation details of the HTTP client out of the components.

Using Axios directly can lead to code duplication and lack of reusability. It also makes the code hard to maintain, especially when changes are needed across multiple components.

The custom useAPI hook simplifies handling API requests by managing API statuses, data, and error states in a clean and concise manner.

You can get 35% off the book 'React the Road to Enterprise' with the code REACTADVANCED.

Thomas Findlay
Thomas Findlay
20 min
25 Oct, 2021

Comments

Sign in or register to post your comment.
Video Summary and Transcription
This Talk covers advanced patterns for API management in large-scale React applications. It introduces the concept of an API layer to manage API requests in a more organized and maintainable way. The benefits of using an API layer include improved maintainability, scalability, flexibility, and code reusability. The Talk also explores how to handle API states and statuses in React, and provides examples of canceling requests with Axios and React Query. Additionally, it explains how to use the API layer with React Query for simplified API management.

1. Introduction to API Management in React

Short description:

Welcome to Advanced Patterns for API Management in Large-Scale React Applications. Today, we'll cover managing API requests in React, handling different API states, creating custom hooks, canceling requests with Axios and React query. Performing API requests in React can lead to code duplication and lack of reusability. To address this, we can implement an API layer. By creating a base API file and importing it into other API files, we can manage API requests in a more organized and maintainable way.

Hello, and welcome to Advanced Patterns for API Management in Large-Scale React Applications. My name is Tomasz Fienli and I'm a full-stack web and mobile developer with nine years of programming experience. I'm a co-owner of Fienli web tech and a mentor and consultant at CodeMentor.io. I'm also the author of Vue and React the Road to Enterprise books, as well as a technical writer for Telerik and the Road to Enterprise blogs.

Now, let's have a look at what we are going to cover today. So, first of all, we will start with how to manage API requests in React in a scalable and flexible manner with an API layer. Then we will see how to handle different API states while performing API requests. We'll also create custom hooks to manage API requests and states, as well as how to cancel requests with Axios and an API layer. Finally, we'll have a look at how to use React query and API layer and how to cancel requests with them.

Okay, so, how can we perform API requests in React? Actually, it's quite simple, right? We can, for instance, use Axios for that. We can just import it and use it in our components. And, well, it can work fine for, let's say, small applications. But there are some issues as the project grows, especially large ones, really. So, what are the main problems with this approach? First of all, code duplication and lack of reusability. Because imagine that we need to, for instance, fetch information about a user, let's say on logging page, register page, and the user profile page. So, all of these would have, well, the same code snippet. So, Axios gets a URL endpoint and so on and so on, right? So, that's not really reusable. And also, well, it's hard to maintain. Because if we had to make any changes to this code, like let's say, for instance, the URL endpoint change or we had to change the payload format, or, let's say, we had to migrate from using Axios to something like Firebase, right? We would need to visit every single component that is Axios and change them. Well, that's not really great, to be honest. So, let's have a look at how we can fix these issues by implementing an API layer. So, first, we would start with a base API file, where we would import Axios and create a new instance with some default configuration, like, for instance, a base URL. Then we have an API function that basically returns API wrapper methods around our Http client, in this case, Axios. And finally, we export it. Next, what we can do is, we can use this base API file and import it in another API file. So, for example, in this case, we'd have users API file. Because we want to do some things with users, like fetch information about users, add a new user, and so on. In this example, we have three methods, list users, get user, and add user. And as you can see, they all use the API methods from the base API file. And how would we use this in a component now? So, basically, what we would do is, we would import an API method from the API directory, and then just use it in a component.

2. API Layer Benefits and Flexibility

Short description:

The API layer in React allows you to abstract away the details of API endpoints and easily switch between different HTTP clients. By separating the API logic into a separate layer, your components remain agnostic to the underlying implementation. This improves maintainability, scalability, and flexibility. You can easily add new API methods, replace the HTTP client, and enhance the API layer with custom logic. Code reusability is also increased, as API methods can be imported and used anywhere in the application. The API layer pattern is framework agnostic, making it suitable for various development environments.

So, as you can see, the component doesn't have to think about what kind of API endpoint has to be hit, right? The API method takes care of that. So, what about if we wanted to use a different HTTP client, like let's say, for instance, Firebase instead of Axios. So, our base API file would look a bit different. So, here, we would just import some necessary Firebase methods, would initialize the Firebase app. And then we would export what we need, for instance, Firebase, Firestore, which gives us methods to basically, well, connecting with the database, and so on, and other things like off storage functions, etc.

Now, in the user API file, we would again have the same methods, like list users, getUser, and addUser. However, in this case, we're using Firebase, of course, right under the hood. But let's have a look at how it would look like from the components perspective now. Well, actually, for the component, nothing would change, because it still would import the API method from the user's API file, and it would just execute it, right? So that's a really great thing about the API layer, because it's like a black box to your components. Because your components don't really have to care about what you use to perform requests. It only is concerned with what methods you should call, what kind of input it should provide, and what kind of output it can expect. As long as you can preserve this input and output contract, you don't need to make any changes to your components. You only need to make changes to the API layer, really.

Now, let's have a look at the benefits of the API layer. First of all, maintainability, as all the API-related code is in one place. Scalability, as you can easily add new API methods and files. And we also have flexibility, it's much easier to replace the HTTP client, and also enhance the API layer with custom logic. So as you've just seen, we replaced access with Firebase and we didn't need to make any changes to the component. Also code reusability, because API methods can be just imported and used anywhere in the application. And the API layer pattern is also framework agnostic.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Routing in React 18 brings a native app-like user experience and allows applications to transition between different environments. React Router and Next.js have different approaches to routing, with React Router using component-based routing and Next.js using file system-based routing. React server components provide the primitives to address the disadvantages of multipage applications while maintaining the same user experience. Improving navigation and routing in React involves including loading UI, pre-rendering parts of the screen, and using server components for more performant experiences. Next.js and Remix are moving towards a converging solution by combining component-based routing with file system routing.
A Framework for Managing Technical Debt
TechLead Conference 2023TechLead Conference 2023
35 min
A Framework for Managing Technical Debt
Top Content
Today's Talk discusses the importance of managing technical debt through refactoring practices, prioritization, and planning. Successful refactoring requires establishing guidelines, maintaining an inventory, and implementing a process. Celebrating success and ensuring resilience are key to building a strong refactoring culture. Visibility, support, and transparent communication are crucial for addressing technical debt effectively. The team's responsibilities, operating style, and availability should be transparent to product managers.
Fighting Technical Debt With Continuous Refactoring
React Day Berlin 2022React Day Berlin 2022
29 min
Fighting Technical Debt With Continuous Refactoring
Top Content
Watch video: Fighting Technical Debt With Continuous Refactoring
This Talk discusses the importance of refactoring in software development and engineering. It introduces a framework called the three pillars of refactoring: practices, inventory, and process. The Talk emphasizes the need for clear practices, understanding of technical debt, and a well-defined process for successful refactoring. It also highlights the importance of visibility, reward, and resilience in the refactoring process. The Talk concludes by discussing the role of ownership, management, and prioritization in managing technical debt and refactoring efforts.
Monolith to Micro-Frontends
React Advanced 2022React Advanced 2022
22 min
Monolith to Micro-Frontends
Top Content
Microfrontends are considered as a solution to the problems of exponential growth, code duplication, and unclear ownership in older applications. Transitioning from a monolith to microfrontends involves decoupling the system and exploring options like a modular monolith. Microfrontends enable independent deployments and runtime composition, but there is a discussion about the alternative of keeping an integrated application composed at runtime. Choosing a composition model and a router are crucial decisions in the technical plan. The Strangler pattern and the reverse Strangler pattern are used to gradually replace parts of the monolith with the new application.
Get rid of your API schemas with tRPC
React Day Berlin 2022React Day Berlin 2022
29 min
Get rid of your API schemas with tRPC
Today's Talk introduces TRPC, a library that eliminates the need for code generation and provides type safety and better collaboration between front-end and back-end. TRPC is demonstrated in a Next JS application integrated with Prisma, allowing for easy implementation and interaction with the database. The library allows for seamless usage in the client, with automatic procedure renaming and the ability to call methods without generating types. TRPC's client-server interaction is based on HTTP requests and allows for easy debugging and tracing. The library also provides runtime type check and validation using Zod.
Step aside resolvers: a new approach to GraphQL execution
GraphQL Galaxy 2022GraphQL Galaxy 2022
16 min
Step aside resolvers: a new approach to GraphQL execution
GraphQL has made a huge impact in the way we build client applications, websites, and mobile apps. Despite the dominance of resolvers, the GraphQL specification does not mandate their use. Introducing Graphast, a new project that compiles GraphQL operations into execution and output plans, providing advanced optimizations. In GraphFast, instead of resolvers, we have plan resolvers that deal with future data. Graphfast plan resolvers are short and efficient, supporting all features of modern GraphQL.

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Top Content
Featured Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
Hands-on with AG Grid's React Data Grid
React Summit 2022React Summit 2022
147 min
Hands-on with AG Grid's React Data Grid
Top Content
WorkshopFree
Sean Landsman
Sean Landsman
Get started with AG Grid React Data Grid with a hands-on tutorial from the core team that will take you through the steps of creating your first grid, including how to configure the grid with simple properties and custom components. AG Grid community edition is completely free to use in commercial applications, so you'll learn a powerful tool that you can immediately add to your projects. You'll also discover how to load data into the grid and different ways to add custom rendering to the grid. By the end of the workshop, you will have created an AG Grid React Data Grid and customized with functional React components.- Getting started and installing AG Grid- Configuring sorting, filtering, pagination- Loading data into the grid- The grid API- Using hooks and functional components with AG Grid- Capabilities of the free community edition of AG Grid- Customizing the grid with React Components
Building GraphQL APIs on top of Ethereum with The Graph
GraphQL Galaxy 2021GraphQL Galaxy 2021
48 min
Building GraphQL APIs on top of Ethereum with The Graph
WorkshopFree
Nader Dabit
Nader Dabit
The Graph is an indexing protocol for querying networks like Ethereum, IPFS, and other blockchains. Anyone can build and publish open APIs, called subgraphs, making data easily accessible.

In this workshop you’ll learn how to build a subgraph that indexes NFT blockchain data from the Foundation smart contract. We’ll deploy the API, and learn how to perform queries to retrieve data using various types of data access patterns, implementing filters and sorting.

By the end of the workshop, you should understand how to build and deploy performant APIs to The Graph to index data from any smart contract deployed to Ethereum.
Database Workflows & API Development with Prisma
Node Congress 2022Node Congress 2022
98 min
Database Workflows & API Development with Prisma
WorkshopFree
Nikolas Burk
Nikolas Burk
Prisma is an open-source ORM for Node.js and TypeScript. In this workshop, you’ll learn the fundamental Prisma workflows to model data, perform database migrations and query the database to read and write data. You’ll also learn how Prisma fits into your application stack, building a REST API and a GraphQL API from scratch using SQLite as the database.
Table of contents:
- Setting up Prisma, data modeling & migrations- Exploring Prisma Client to query the database- Building REST API routes with Express- Building a GraphQL API with Apollo Server