Header image

A Better Way To Use Services In React Application

31/08/2022

5.54k

Vix Nguyen

Sometimes you have/want to create and use a service in your application for the DRY principle. But do you know exactly what is a service? And what is the best way to use services in React applications?

Services In React Application

Hi everyone! It’s nice to meet you again in React related series. In the previous article, we discussed about effective state management in React, we learned about Context: what is it? when to use it? One of the use cases is using a context to share a collection of services through the components tree, but what kind of things can be called a service? And how is it integrated into React application? Let’s discover the following sections:

What is a Service?

Service is just a group of helper functions that handle something particularly and can be reused across application, for example:

  • Authentication Service that includes authentication status checking, signing in, signing out, getting user info …
  • Http Service that handles request header, request method, request body …

How to use?

There are different kinds of implementation and usage, I just provide my favorite one that follows Angular module/services provider concepts.

Create a service

A service is a JavaScript regular class, nothing related to React.

export default class ApiService {
  constructor() {}

  _setInterceptors() {}

  _handleResponse_() {}

  _handleError_() {}

  get() {}

  post() {}

  put() {}

  delete() {}
}
export default class AuthService {
  constructor() {}

  isAuthenticated() {}

  getUserInfo() {}

  signIn() {}

  signOut() {}
}

Create a Context

Create a context with provider and pass services as props.

import { createContext, useState } from 'react';
import { ApiService, AuthService } from '@services';

const services = {
  apiService: new ApiService(),
  authService: new AuthService()
};

const AppContext = createContext();
const { Provider } = AppContext;

const AppProvider = ({ children }) => {
  return <Provider value={{ services }}>{children}</Provider>;
};

export { AppContext, AppProvider }

Use a context

Place a context provider at an appropriate scope, all consumers should be wrapped in it.

import { AppProvider } from './context/AppContext';
import ComponentA from './components/ComponentA'

const App = () => {

  return (
    <AppProvider>
      <div className="app">
        <ComponentA />
      </div>
    </AppProvider>
  );
};

export default App;

Inside a child component, use React hooks useContext to access services as a context value.

import { useContext, useEffect } from 'react';
import { AppContext } from '../context/AppContext';

const ChildComponent = () => {

  const { 
    services: { 
      apiService,
      authService
    } 
  } = useContext(AppContext);

  useEffect(() => {
    if (authService.isAuthenticated()) {
      apiService.get();
    }
  }, []);

  return <></>;
}

export default ComponentA;

Above are simple steps to integrate services with context. But it would be complicated in the actual work. Consider organizing context with approriate level/scope. My recommendation is to have two kinds of service contexts in your application:

  • App Services Context to put all singleton services. Bootstrap it once at root, so only one instance for each is created while having them shared over the component tree.
  • For others, create separate contexts and use them anywhere you want and whenever you need.

Alternatives

Service is not the only one way to deal with reusable code, it depends on what you intend to do, highly recommend to:

  • Use a custom hook, if you want to do reusable logic and hook into a state.
  • Use a Higher-order component, if you want to do the same logic and then render UI differently.

Reference

Author: Vi Nguyen

Related Blog

Our culture

+0

    From Seeking The Path to Leading The Way: Phuoc’s Journey at SupremeTech

    Are you curious how someone with no IT background made a bold leap into tech and ended up leading a team? Starting with no formal IT background, Phuoc took a leap of faith into the world of Infrastructure at SupremeTech. What began as a fresh start during the pandemic has become an inspiring tech career journey from entry-level newcomer to the leader of our Infrastructure team. In this inspiring interview, Phuoc shares the lessons learned, the power of making mistakes, and how embracing challenges helped shape his career in tech. First Impressions That Last Hi Phuoc! What was your first impression when you joined SupremeTech?I still remember my first day at SupremeTech. What impressed me most… was the smell of a brand-new office! (laughs)It might sound funny, but that paint smell felt comforting. It reminded me of my first job after graduation, working at a new construction site—filled with excitement, hope, and anticipation. Whenever I catch that same scent, it brings back the feeling of a fresh start. From Tourism to Tech: A Career Switch Sparked by Fate We heard you used to work in the tourism industry. What made you switch to IT?Yes, I worked as an admin in the tourism sector. Shifting careers felt like fate. Honestly, it might sound silly, but I chose SupremeTech mainly because they offered a MacBook! (laughs).At the time, I was looking to change my career to IT Infrastructure and had passed interviews at two companies. But when I discovered SupremeTech would provide a MacBook, I was so excited I couldn’t say no.Back then, I felt like a blank sheet of paper. Starting in a completely new field was a huge challenge. But thanks to the support from my teammates, I slowly adapted and began to grow. Starting During COVID: Remote Work and Early Struggles Changing industries isn’t easy. What was the toughest challenge for you?I joined SupremeTech during the COVID pandemic, so the biggest challenge was starting remotely. I didn’t know anyone, and everything was done over Google Meet. Building connections, understanding the work, or communicating effectively was hard. When we finally returned to the office, I was so happy to meet my teammates, mentors, and colleagues in person. That’s when my real learning journey began.One of the most memorable challenges? Making mistakes. I’ve never been afraid of being wrong—in fact, I enjoy it. I made many mistakes initially, but each one taught me something. Most of them happened because I didn’t think far enough ahead. Over time, I learned to be more thoughtful and less overconfident. Lessons from Mistakes: Learning the Hard Way How did you manage to get through those mistakes?Mistakes are valuable lessons. Now, I even create small “traps” in internship assignments based on the mistakes I once made. It helps them encounter real problems and learn through hands-on experience. You remember things better when you figure them out yourself, rather than just reading about them. After every project, our team writes a retrospective report noting what could have been done better. One mistake equals one lifelong lesson. Facing Challenges with a Grateful Mindset You talk a lot about challenges—what does that word mean to you?To me, challenges are a kind of “fate”. They don’t just happen by chance. You have to find a way to overcome them when they show up.They might feel overwhelming at the moment, but when I look back, I feel grateful—even thankful for the people who gave me those challenges. Every company has its problems. What matters is how you deal with them and what you learn along the way. From Fresher to Team Leader: A Role Earned Through Action You’re a team leader now. How did that role come to you?Honestly, I didn’t expect to become a leader so soon. But I’ve never been the type to wait around for task assignment. At the associate level, I tried to help interns and share my experience. I focused on building strong communication and genuine connections.As a mentor, I always try to lead by example. So when I was promoted, I already felt ready. When you sincerely help others, good things naturally come your way. A Culture of Calm and Growth What’s something special about the work environment at SupremeTech?SupremeTech has a very peaceful work environment. There’s no office politics or unnecessary drama. It’s a safe and supportive place where people can grow. But that doesn’t mean the work is easy. During projects, it can feel like going into battle. Everyone has to stay sharp and take ownership to solve problems. It’s an outstanding balance—our culture is kind, but our work ethic is fierce. That reflects SupremeTech's core values: be kind in life and embrace Passion and Challenge at work. Words of Advice for Young IT Professionals What would you say to young people just starting their careers in IT?Make mistakes while you still can. Don’t be afraid to be wrong. You’ll learn more from your errors than from any books.Don’t be afraid to try. Don’t avoid difficult things, especially if you want to grow beyond your comfort zone. Looking Back: Any Regrets? Looking back at your tech career journey, do you have any regrets?Not at all. Every step I’ve taken has been worth it. Skills are essential, but the environment shapes who you become. I love investigating new problems and finding solutions. My curiosity has given me more experiences than most people at my level haven’t had, which helps me grow every day. Final thought Thank you, Phuoc, for sharing your honest and inspiring story. We wish you continued passion, positivity, and success on your tech career journey with SupremeTech!

    11/04/2025

    51

    Our culture

    +0

      From Seeking The Path to Leading The Way: Phuoc’s Journey at SupremeTech

      11/04/2025

      51

      Our success stories

      +0

        How to Upgrade Aurora MySQL Databases: Lessons Learned from SupremeTech

        Upgrading a critical database like Aurora MySQL can feel daunting. We want better performance and a smooth system, but downtime and data risks can loom large. At SupremeTech, we’ve tackled this challenge head-on and shared our proven approach.  This insight comes from Mr. Phuoc Pham, our Infrastructure Manager, who presented at the morning session of "Harnessing AI on AWS: Transforming Software Builders for the Future" event by AWS and MegazoneCloud. The event focused on giving software companies tools, strategies, and real-world solutions to innovate, boost performance, and grow globally with AI. In his talk, Mr. Phuoc revealed our 6-step process that minimizes risks, protects data, and increases efficiency. Here’s how we did it, key lessons learned, and how you can ensure a smooth and risk-free database upgrade. Mr. Phuoc Pham, our Infrastructure Manager, presented the lesson learned from Aurora MySQL upgrades SupremeTech’s contribution to the AWS and Megazone event SupremeTech partners with AWS and MegazoneCloud to share our expertise in tackling technical challenges. In the morning session, Mr. Phuoc Pham delivered a presentation on lessons learned from Aurora MySQL upgrades, offering practical tips for software companies to optimize their infrastructure. In the afternoon, our chairman, Mr. Truong Dinh Hoang, joined a panel discussion on future trends for ISVs, highlighting strategies for growth and innovation. These contributions underscored SupremeTech’s commitment to helping businesses enhance performance and scale smarter. In the afternoon panel discussion, Mr. Truong Dinh Hoang shared about the market expansion and future trends for ISVs. The Challenges of Upgrading Aurora MySQL Mr. Phuoc kicked off by sharing real-world challenges we faced with a client’s Aurora MySQL upgrades: Minimal downtime: We had to finish in under 2 hours, including rollback time if needed.System stability: Our database powers multiple services, so it had to stay reliable post-upgrade.Fast rollback: We needed a quick way to revert without losing data if something went wrong.User impact: Our process had to keep disruptions low and customer trust high. These hurdles might sound familiar if you’ve upgraded a system. The key to achieving this is a structured and well-tested upgrade process. Mr. Phuoc Pham presented the challenges of upgrades for our client’s system. The 6-Step Database Upgrade Process At SupremeTech, we follow a 6-step upgrade process to ensure a smooth transition. Step 1: Collect and Analyze Data Before the Upgrade Preparation is everything. Before making any changes, assessing your current database setup is essential. This helps identify potential risks and prepare for a smooth transition. Mr. Phuoc emphasized checking: Database Schema & Objects – Make sure there are no conflicts with the new version.Connected Applications – Identify all services using the database.Custom Database Settings – Compare parameter changes between versions.Performance Metrics – Monitor CPU, memory, query latency, and transaction speed. We gather this information using tools like database logs, security groups, and queries like SHOW FULL PROCESSLIST. This step prepares us for a smooth upgrade. Mr. Phuoc shared one of our 6-step upgrade processes. Step 2: Choose the Right Upgrade Method with C.I.D.D.E.R Framework Not all upgrade methods are the same. Depending on your system’s needs, you may choose one of the following: Snapshot Restore – Reliable but requires full backup and longer downtime.Clone Cluster – Fast rollback but requires additional storage.In-Place Upgrade – Minimal downtime but higher risk.Blue/Green Deployment – Safest rollback option but costly. At SupremeTech, we use the C.I.D.D.E.R framework to decide the best method based on: Complexity: How hard is the upgrade?Infrastructure Cost: What’s the budget hit?Downtime: How long will it take?Dependencies: What else relies on our database?Expertise: Do we have the skills?Rollback Strategy: How easy is it to undo? Choosing the right upgrade method can reduce risk and save time. For this case—a 10GB database, multiple services, and a team still building experience—we chose an in-place upgrade with a clone cluster backup for quick rollback by renaming the database cluster. It kept the endpoint intact and downtime under 2 hours. Step 3: Test with a Dry Run “There’s no place like production,” Mr. Phuoc quipped, stressing the need for practice.  A dry-run is a test upgrade performed in a staging environment to catch problems before they affect real users. We run dry runs on a cloned database and DEV/STG environments to: Detects issues before they impact production.Reduces unexpected downtime.Helps estimate the actual upgrade time. This extra step can save hours of troubleshooting later. Step 4: Fine-Tuning Based on Dry-Run Results After testing, we adjust the process: Adjust database settings.Fix errors from the dry run.Shorten execution time for less downtime.Refine rollback procedures.Update guides for our team. A few small tweaks before the upgrade can prevent major issues after it. Step 5: Deployment – The Actual Upgrade With everything tested and fine-tuned, it's time to execute the upgrade in production. How we ensure success: Perform the upgrade during low-traffic hours.Keep the rollback plan ready.Monitor logs in real time for any errors. Having a clear step-by-step deployment plan prevents last-minute surprises. Step 6: Monitor After the Upgrade Post-upgrade, we track key metrics like: Resources: CPU, memory, disk usage.Performance: Query response time, QPS, TPS.Errors: Any glitches or slow queries.Data Integrity: No data loss or corruption. Continuous monitoring after the upgrade helps us spot issues quickly, reducing troubleshooting time and minimizing the impact on our customers. We monitor key performance metrics for both the new and old databases to compare. We also watch the four golden signals—latency, traffic, errors, and saturation—to get a full picture of system health. At SupremeTech, we use AI-powered tools like Amazon Q to analyze database logs and detect anomalies faster than manual monitoring. Why post-upgrade monitoring matters: Quickly identifies hidden performance issues.Ensures the upgrade was 100% successful.Helps optimize for better database efficiency. Boosted performance and customer trust are critical criteria when we implement upgrades. Results & Lessons Learned Our Results By following this 6-step process, SupremeTech successfully upgraded Aurora MySQL with: Done in under 2 hours of downtime.Lowered infra costs with smarter planning.Boosted performance and customer trust. Key Takeaways Mr. Phuoc wrapped up with these gems: Prep is everything: Gathering and analyzing info before the upgrade is critical to spot risks early.Plan for data checks: We ensure data integrity with a solid verification plan.Pick the right approach: We choose deployment and rollback methods that fit our clients’ operations.Keep monitoring: Continuous tracking helps us stay ahead of issues.Automate with AI: Using AI and tools speeds us up and cuts errors. Wrapping Up Upgrading a database doesn’t have to be a risky, stressful process. You can confidently upgrade with the right preparation, testing, and monitoring. Thanks to Mr. Phuoc Pham’s presentation at the AWS and MegazoneCloud event, our 6-step process at SupremeTech proves you can keep risks low, protect data, and emerge stronger when doing Aurora MySQL upgrades. If your company is planning a database upgrade and needs expert guidance, contact our team at SupremeTech. We help businesses upgrade critical databases without disruption. Want to learn more about cloud database best practices? Stay tuned for more insights from our tech experts! Related articles about AWS: Mastering AWS Lambda: An Introduction to Serverless ComputingCreate Your First AWS Lambda Function (Node.js, Python, and Go)Triggers and Events: How AWS Lambda Connects with the WorldBest Practices for Building Reliable AWS Lambda Functions

        21/03/2025

        121

        Our success stories

        +0

          How to Upgrade Aurora MySQL Databases: Lessons Learned from SupremeTech

          21/03/2025

          121

          Our success stories

          +0

            SupremeTech Partners with AWS and MegazoneCloud to Drive AI-Powered Business Growth

            SupremeTech is pleased to announce our collaboration with AWS and MegazoneCloud for an upcoming event, Harnessing AI on AWS: Transforming Software Builders for the Future, scheduled for March 20, 2025, in Da Nang. This event is about giving software companies the tools, strategies, and real-world solutions they need to spark innovation, boost performance, and even take their businesses global with AI. The software world is changing fast, and Artificial Intelligence is leading the charge. Companies that tap into AI on AWS are finding new ways to grow, streamline their workflows, and stay ahead of the game. This event offers software firms in Da Nang and beyond the chance to see how AI can level up your business and prepare them for the future. SupremeTech’s Contribution to the Event In partnership with AWS and MegazoneCloud, SupremeTech will share valuable insights from our experience mastering complex technical challenges, such as Aurora MySQL upgrades. We will break it down into practical tips and solutions that software companies can use to fine-tune their infrastructure and grow smarter. The SupremeTech partners with AWS and MegazoneCloud event is structured into two key sessions: Morning Session: Accelerating Technical Performance Enhancing Product Value with AI/ML Services: Attendees will learn how AWS’s advanced tools, including Amazon SageMaker and Bedrock, can optimize infrastructure, improve performance, and reduce time to market.Real-World Solutions: Megazone will present hands-on demonstrations of AI services on AWS, offering insights into seamless integration and proven strategies derived from their own expertise. Afternoon Session: Strategic Growth Expansion Scaling with AWS Programs: Discover how AWS initiatives such as the ISV Accelerate and Workload Migration Program (WMP) can accelerate market expansion and support rapid business growth.Global Opportunities with MegazoneCloud: Explore how MegazoneCloud’s extensive partner network and the AWS ecosystem can help software companies bring their products to international markets. This event is more than a technical gathering; it represents a strategic opportunity for software businesses to advance their capabilities and adopt AI effectively on AWS. Why You Should Attend Actionable Strategies: Gain practical knowledge to integrate AI into your business operations.Expert Insights: Benefit from the expertise of SupremeTech, AWS, and MegazoneCloud leaders with proven success in the AI landscape.Networking: Connect with industry peers and potential partners within Da Nang’s growing tech community.Global Expansion: Access tools and programs to scale your business internationally. Event Details Date: March 20, 2025Location: Voco Ma Belle Danang - 168 Vo Nguyen Giap Street, Son Tra Da Nang, Vietnam Register Today to Stay Ahead in the AI Era Do not miss this opportunity to leverage AI on AWS and position your software business for success. Join the event that SupremeTech partners with AWS and MegazoneCloud on March 20, 2025, to grab the insights and tools you need to lead the charge in innovation and growth. Click Here to Register Now and take the first step toward a future of innovation and growth. Related articles about AWS: Mastering AWS Lambda: An Introduction to Serverless ComputingCreate Your First AWS Lambda Function (Node.js, Python, and Go)Triggers and Events: How AWS Lambda Connects with the WorldBest Practices for Building Reliable AWS Lambda Functions

            11/03/2025

            160

            Ngan Phan

            Our success stories

            +0

              SupremeTech Partners with AWS and MegazoneCloud to Drive AI-Powered Business Growth

              11/03/2025

              160

              Ngan Phan

              E-commerce (Shopify)

              +0

                How to Build a High-Performing E-commerce Store

                E-commerce is growing every year and is set to make heavy profits, with more and more people opting for it. However, with ever-growing competition in this domain, you need to stand out to stay afloat. You have to compete with giants like Amazon, eBay, and Alibaba, which can give you a tough time. In this blog, we will discuss building a high-performing e-commerce store in detail. So, let’s get started. See more: Exploring 7 Top Online Food Ordering Systems for Small BusinessesSmooth Sailing: How to Migrate Website to Shopify? Step-by-Step Procedure for Building an E-commerce Store E-commerce stores are becoming increasingly popular due to their range of products on a single platform, short delivery time, and easy payment options. Let’s go through a step-by-step procedure for building an attractive and high-performing e-commerce store. Step 1: Choose Your Platform Each e-commerce store is unique and has its own goals and target audience. Hence, you need to choose an ideal e-commerce platform for your needs. There are a number of options available including Shopify, WooCommerce, Squarespace, WordPress and more.  These eCommerce platforms have their own features, so you should discuss each one with your development team and pick the most suitable one for your needs. Step 2: Create an Account on the Chosen Platform Once you have chosen your eCommerce store platform, you need to purchase the subscription, in case it is not open source. These platforms offer a variety of plans, uptime guarantees, and security features.  If you have chosen an all-in-one e-commerce platform, all you need to do is go to the provider’s website and create an account. Then, you select a plan and pay for it if it is not free. Step 3: Choose a Template After you have decided on your eCommerce platform, you will have a variety of options regarding templates. Each has its own colors, fonts, and layouts, which gives an e-commerce store a consistent look and feel. Templates can be free or premium ones, for which you need to pay. Generally speaking, paid ones offer more features and designs. This saves time which will be spent on coming up with designs from scratch. Step 4: Build Your Webpages & Product Pages You must not use the template as it is; you should customize it according to your requirements. Some common customizations include adding your logo and contact details.  Other changes could be adding product images, configuring your site navigation, and building check-out and returns pages. Step 5: Write Product Descriptions As it is not a brick-and-mortar store where customers can view the products or feel them, you need to work on your product descriptions along with images. They need to be very accurate, easy to understand, and detailed. It should include basic details, along with information about who the product is meant for and where it can be used.  Product images should be high-definition and of the same size, and should show the product from all possible angles.  Step 6: Set Up Payment Gateway As most of your customers will opt for online payments and not Cash on Delivery, you need to have a secure payment gateway. So, integrate secure payment options on your e-Commerce store, which are hassle-free, fast and secure at the same time.  If you redirect your customers to other platforms like PayPal, ensure that data is fully encrypted.  If your payment options are not convenient, no matter how good your product catalog is, customers will not come back. Step 7: Integrate Shipping  The platform you have chosen for your e-Commerce store may allow integrated shipping along with selling. This creates a seamless customer experience and lets you focus on selling products.  You also need to decide on your shipping policy, such as free shipping, flat rates, variable fees, etc. Along with this, you need to decide on your returns and refund policy to make the situation clear for your customers. Step 8: Test & Launch Your e-Commerce Store After all the hard work, it is time to test your e-commerce store before launching it. You should do rigorous testing to ensure there are no bottlenecks and pain points. You can do the testing in-house or outsource the task.  Check all links, buttons, and navigation options and ensure they work. Payment processing should also be thoroughly checked. Your e-commerce store should be compatible with desktop, mobile devices, and all browsers. Once everything has been checked, you are ready for launch. Popular eCommerce Platforms To Consider Several options are available for e-commerce platforms. Let’s discuss some popular ones to help you choose. Shopify Shopify is an eCommerce platform suitable for Web, iOS, and Android. It is easy to set up and has all the necessary tools. The support and resources provided are best in class, which makes it popular and effective.  The only constraint of Shopify is that it can be expensive if you add many extra apps. Many eCommerce stores currently run on Shopify, which has been around for 18 years and is ideal for small businesses that want to go online. BigCommerce BigCommerce is an e-commerce platform suitable for Web, iOS, and Android devices. It is the SMB version of a very popular enterprise eCommerce platform. It has integrated features like shipping and taxes to encourage established businesses online. However, it is not recommended for small retailers setting up their businesses.   It also enables listing your products on e-commerce giants like eBay, Walmart, and Amazon.  As a result, customers do not necessarily have to buy from your store.   BigCommerce has 12 free themes, all of which have a great look. They also have a drag-and-drop site builder that can be used to customize the look.  WooCommerce   WooCommerce is an e-commerce platform for the Web, iOS, and Android. It provides all the flexibility of WordPress, is widely supported, and has many apps and integrations. Installing WooCommerce on your website is very easy, similar to installing any  other plugin on WordPress. If you use WordPress for your eCommerce store, you should ideally go for WooCommerce. Wrapping Up E-commerce is still nascent and will continue to grow over the decade. It provides a range of products and the convenience of buying them from your home from across the world. So, whether you are starting or have an established business, you should consider going online, as it will increase your reach. After considering everything, you should choose your e-commerce store platform. This will ensure that you have a high-performing e-commerce store. For building your e-Commerce store, get in touch with SupremeTech. 

                10/03/2025

                94

                E-commerce (Shopify)

                +0

                  How to Build a High-Performing E-commerce Store

                  10/03/2025

                  94

                  Customize software background

                  Want to customize a software for your business?

                  Meet with us! Schedule a meeting with us!