Header image

How-To

Tech news

A Better Way To Use Services In React Application

31/08/2022

2.15k

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

nativescript vs react native for cross-platform mobile development

Knowledge

+0

    NativeScript vs React Native: Comparing Cross-Platform Mobile Development Frameworks

    Hi tech fellows, the comparison series continues to dive in mobile development frameworks. This-week candidates call out NativeScript vs React Native. Both of them offer developers the ability to build apps that run seamlessly on both iOS and Android devices. So let's explore the similarities and differences in this article and make an informed decision when choosing a best fit for your project. Here are the six criteria to compare: Language and Development EnvironmentPerformance and User ExperienceUI Components and CustomizationDevelopment environmentCommunity and Ecosystem SupportPlatform Support and Integration Language and Development Environment NativeScript allows developers to write applications using JavaScript or TypeScript. It provides access to native APIs using JavaScript. React Native uses JavaScript and React, a popular JavaScript library for building user interfaces. Developers write components in JavaScript which are then compiled to native code. Both NativeScript and React Native empower developers to build cross-platform mobile applications using popular programming languages. NativeScript supports JavaScript and TypeScript, while React Native utilizes JavaScript and the React library. This means developers can leverage their existing skills and knowledge to kickstart their projects. Performance and User Experience NativeScript apps are compiled to native code, which generally provides better performance compared to hybrid frameworks. However, there might be some overhead due to the bridge between JavaScript and native code. React Native also compiles down to native code, but it uses a JavaScript bridge to communicate with native components, which might introduce some performance overhead. UI Components and Customization NativeScript provides UI components that map directly to native components, allowing for a truly native look and feel. It provides a large set of UI components out of the box. React Native also provides access to native UI components, but its component library might not cover all native features. However, it offers a vast ecosystem of third-party libraries and components. Development Environment NativeScript can be used with various development environments including Visual Studio Code, WebStorm, and others. It provides a CLI for project setup and management. React Native has a strong community and excellent tooling support. It comes with tools like Expo and React Native CLI for project setup and management. Community and Ecosystem NativeScript has a smaller community compared to React Native but still has a vibrant ecosystem with plugins and community support. React Native has a large and active community, which means more resources, tutorials, and third-party libraries available. While React Native boasts a larger community and ecosystem compared to NativeScript, both frameworks benefit from active developer communities and extensive documentation. This means you'll have access to resources, tutorials, and support channels to help you overcome challenges and streamline your development process. Whether you're a seasoned developer or just starting, the wealth of resources available for both frameworks ensures you're never alone on your development journey. Platform Support and Integration NativeScript supports iOS and Android platforms. It also provides some level of support for building web applications. React Native primarily targets iOS and Android platforms, but with the help of libraries like React Native Web, it's possible to target web browsers as well. Additionally, both frameworks offer mechanisms for integrating with native code when necessary, enabling you to access platform-specific features and functionalities. Whether you're targeting a specific platform or aiming for broad compatibility, both NativeScript and React Native provide the tools you need to succeed. NativeScript vs React Native: What should you choose? In conclusion, both NativeScript and React Native offer compelling solutions for cross-platform mobile app development. While NativeScript provides a more native approach with direct access to native APIs and UI components, React Native offers a familiar development experience with its use of JavaScript and React. Ultimately, the choice between NativeScript and React Native depends on your specific project requirements, familiarity with the respective technologies, and personal preferences. Whichever framework you choose, you can rest assured knowing that you're equipped with powerful tools and a supportive community to help you bring your mobile app ideas to life. Or if you need an expert to guide you through, we are here to help! Book a free consultation with us and share your pain-points. Thanks for reading! See you in the next article!

    03/04/2024

    68

    Knowledge

    +0

      03/04/2024

      68

      NativeScript vs React Native: Comparing Cross-Platform Mobile Development Frameworks

      OTT App development

      Tech news

      +0

        OTT App Development: Navigating The Common Revenue Models

        As Over-The-Top OTT app development reshapes media consumption, understanding its revenue landscape is crucial. Explore the intricacies of OTT app revenue models, including subscription-based, advertising-based, and transactional approaches. Discover how technological advancements, like AI and secure payment gateways, are impacting revenue generation. Learn how to overcome challenges and maximize profits in this dynamic industry. Overview of OTT Apps Development Over-The-Top (OTT) app development is revolutionizing the way we consume media and entertainment. These apps, which deliver video content directly over the internet, bypass traditional distribution channels such as cable or satellite TV. They are growing in popularity due to their convenience, as they allow users to access a vast variety of content anytime, anywhere, on any device. Additionally, they offer innovative monetization strategies that are reshaping the revenue landscape of the entertainment industry. Understanding the Revenue Landscape The revenue landscape for OTT apps is complex and multi-faceted. It entails a variety of revenue models, each with its own unique advantages and challenges. These models determine how the apps generate income, whether it's through user subscriptions, advertising, or pay-per-view transactions. Understanding these models is essential for any business looking to thrive in the OTT space. OTTs app development - Revenue Landscape Key Revenue Models for OTT Apps Custom OTT platforms primarily utilize three revenue models: subscription-based, advertising-based, and transactional models. Subscription-based Model The subscription-based business model is a popular choice in the world of Over-The-Top (OTT) applications. This model, which requires users to pay a subscription fee either monthly or yearly, provides access to a comprehensive library of content. By subscribing, users can enjoy a wide variety of content from different genres and formats, making it a one-stop solution for their entertainment needs. This model is beneficial for the service providers as well, as it guarantees a consistent revenue stream. This predictability of income allows these platforms to invest in acquiring new content, improving their services, and even producing their own original content. Major platforms like Netflix and Hulu use this model. They offer a diverse range of content including movies, TV series from various networks, and their own original productions. OTTs app development - SVOD model Advertising-based Model In the advertising-based model, users get to view the content for free. However, this content comes with advertisements in between. The money comes from these advertisements. Advertisers pay to display their ads within the content. YouTube is a great example of this model. It features content from users, music videos, and more. From a development viewpoint, this model needs strong ad-serving technologies. It also requires algorithms to ensure ads are placed at the right spots. These measures help to increase ad views and clicks, leading to higher revenue. OTTs app development - AVOD model Transactional Model The transactional or pay-per-view model is a revenue strategy in which users make payments for each piece of content they consume. This approach is prevalent on platforms like Amazon Prime, primarily for renting or buying individual movies. It's especially effective for offering premium or exclusive content that users are inclined to pay additional charges for. This model necessitates a reliable and secure payment gateway, along with a robust content delivery network to ensure seamless access to premium content. A well-structured database to manage individual user transactions and preferences is also crucial for personalized content delivery. Challenges in Navigating the Revenue Landscape - Maximizing profit In the OTT app development world, making money can be a big challenge. Developers need to set the right prices to keep users and stay profitable. They also have to deal with content rights, which can be complicated, especially when dealing with different countries. The OTT app development market is also getting more competitive with new players entering all the time. To maximize revenue, it's important to know your audience, choose the right revenue model, and keep improving your app. Staying up to date with market trends and user preferences is also vital. Furthermore, using analytics to understand user behavior and preferences can help in creating personalized experiences and content suggestions, which can increase user engagement and keep them coming back. OTTs app development The Impact of Technological Advancements on OTT Revenue Technological advancements have a profound impact on the OTT revenue landscape. For instance, the advent of artificial intelligence (AI) and machine learning (ML) technologies has enabled OTT platforms to offer personalized content and advertisements, leading to increased user engagement and thereby, higher revenue. Also, the development of secure payment gateways has made transactions more straightforward and safer, encouraging more users to opt for premium content or subscriptions. Conclusion OTT apps have transformed the way we consume media and entertainment, offering users an unprecedented level of convenience and choice. By understanding the revenue landscape and adopting the right strategies, businesses can tap into the immense potential of OTT apps and achieve sustainable growth. Ready to revolutionize your media business and maximize revenue? Explore our comprehensive OTT solution tailored to meet your needs. With subscription-based, advertising-based, and transactional models integrated seamlessly, along with cutting-edge technologies to enhance user engagement and monetization, our OTT solution empowers you to navigate the revenue landscape effectively. Take the next step towards success in the OTT industry today!

        27/03/2024

        98

        Tech news

        +0

          27/03/2024

          98

          OTT App Development: Navigating The Common Revenue Models

          Online-to-Offline Retail

          Knowledge

          +0

            Seamless Retail Bliss: Online-to-Offline Retail with Reserve Online, Pay In-Store

            Online-to-Offline (O2O) retail seamlessly blends digital and physical shopping, catering to modern consumers' preferences. Recognizing the importance of both online convenience and in-person engagement, O2O enables effortless transitions between virtual and real-world experiences. Among 13 commonly-used strategies, Reserve Online, Pay In-Store (ROPIS) is a top key strategy. It allows customers to reserve items online and complete transactions in physical stores, offering added convenience and improved inventory management. However, implementing ROPIS requires addressing security and logistical challenges. Nonetheless, by ensuring a seamless customer journey, ROPIS enhances overall satisfaction and loyalty in the O2O retail landscape. Online-to-Offline (O2O) retail effortlessly merges digital and physical shopping, meeting the changing needs of modern consumers. It enables shoppers to start online, browsing products digitally, and seamlessly transition to in-store experiences. O2O - Reserve Online, Pay In-Store O2O acknowledges the benefits of both online convenience and in-person engagement, allowing consumers to switch between virtual exploration and real-world interaction effortlessly. By combining online and offline strengths, O2O retail delivers unified shopping experiences, building stronger brand connections and catering to the diverse preferences of today's shoppers. So what is Reserve Online, Pay In-Store (ROPIS)? In the previous article, we have mentioned 13 Commonly-Used Strategies, and Reserve Online, Pay In-Store is one of the most common one a business might take a look. A short definition… ROPIS (Reserve Online, Pay In-Store) transforms the Online to Offline (O2O) shopping experience by enabling customers to reserve their desired items online and finalize their transactions in physical stores. O2O - Reserve Online, Pay In-Store With ROPIS, shoppers can browse and select products from the comfort of their homes or on-the-go, securing their purchases digitally before heading to the store for a seamless checkout process. Enhancing the O2O Shopping Experience with ROPIS This not only simplifies the purchasing process but also ensures that the desired items are available upon arrival, enhancing customer satisfaction and loyalty. Let’s get dive in: Reserve Online, Pay In-Store ROPIS: A Seamless Shopping Solution ROPIS (Reserve Online, Pay In-Store) bridges the gap between the Online to Offline (O2O) shopping experience, empowering customers to effortlessly reserve their preferred items online and complete their transactions in physical stores. This approach introduces a convenient and flexible dimension to shopping, as customers can browse and select products digitally at their convenience and then seamlessly transition to the tactile in-store environment for finalizing their purchases. Benefits for Consumers and Retailers ROPIS (Reserve Online, Pay In-Store) offers a multitude of benefits for both customers and retailers, enhancing the Online to Offline (O2O) shopping landscape. For shoppers, ROPIS provides added convenience and flexibility by allowing them to reserve products online and complete their purchases in-store, aligning seamlessly with their preferences and schedules. Moreover, by streamlining the shopping process, ROPIS reduces the incidence of abandoned carts and ensures product availability, thereby enhancing customer satisfaction. O2O - Reserve Online, Pay In-Store benefit On the retailer side, ROPIS facilitates improved inventory management and increased foot traffic, as customers are incentivized to visit physical stores to finalize their purchases. This convergence of online convenience and offline engagement not only fosters stronger customer relationships but also drives sales and business growth in the dynamic O2O retail environment. How ROPIS Enhances the O2O Shopping Experience Convenience for Customers Reserve Products Online Customers can browse and reserve products online at their convenience, eliminating the need to visit multiple stores in search of desired items Reserve Products Online - Customers can browse and reserve products online at their convenience, eliminating the need to visit multiple stores in search of desired items.Seamless Transition to In-Store Experience - Upon arrival at the store, customers enjoy a seamless transition from their online browsing experience to the tactile exploration of products, enhancing overall satisfaction. Flexibility in Payment Secure Payment Options ROPIS offers secure payment options, ensuring peace of mind for customers when finalizing their purchases in-store.Ability to Utilize In-Store Discounts and Promotions Customers can take advantage of in-store discounts and promotions when completing their purchases, maximizing savings and enhancing the overall value proposition. Improved Inventory Management Reduction of Abandoned Carts By allowing customers to reserve products online, ROPIS significantly reduces the incidence of abandoned shopping carts, leading to higher conversion rates and increased revenue.Enhanced Customer Satisfaction Through Product Availability Retailers can better manage their inventory and ensure product availability, thereby enhancing customer satisfaction and loyalty. Overcoming Challenges and Concerns Addressing Security and Privacy Issues Ensuring the security and privacy of customer data is paramount for retailers as they implement Online to Offline (O2O) strategies like ROPIS (Reserve Online, Pay In-Store). O2O - Reserve Online, Pay In-Store - enhance shopping experience By safeguarding against potential threats and adhering to stringent privacy measures, retailers can instill confidence and trust among shoppers. This trust is essential for fostering long-term customer relationships and encouraging continued engagement with the O2O retail ecosystem. Moreover, prioritizing data security not only protects customers but also safeguards the reputation and integrity of the retailer's brand, demonstrating a commitment to ethical business practices in an increasingly digital world. Managing Inventory and Fulfillment Logistics Efficient inventory management and seamless fulfillment logistics play a pivotal role in ensuring the success of Online to Offline (O2O) strategies such as ROPIS (Reserve Online, Pay In-Store). This necessitates a harmonious coordination between online and offline operations to ensure that products reserved online are readily available for in-store purchase. This seamless integration not only enhances the customer experience but also optimizes operational efficiency, laying the foundation for sustainable growth and profitability in the dynamic O2O retail landscape. Ensuring a Seamless Customer Journey Across Channels Creating a seamless and cohesive customer journey across both online and offline channels is imperative for retailers operating in the Online to Offline (O2O) landscape. This entails minimizing friction points and optimizing every touchpoint of the shopping experience to ensure consistency and convenience for customers. By integrating online and offline channels seamlessly, retailers can provide customers with the flexibility to browse, purchase, and engage with their brand across multiple platforms effortlessly. Whether customers choose to interact digitally or in-person, maintaining consistency in branding, product information, and service quality is key to fostering trust and loyalty. Conclusion Reserve Online, Pay In-Store emerges as a game-changer in the realm of O2O retail, offering unparalleled convenience, flexibility, and satisfaction to both customers and retailers alike. As the retail landscape continues to evolve, ROPIS stands poised to shape the future of shopping, elevating the overall shopping experience to new heights of excellence. Customize your own Reserve Online, Pay In-Store strategy with SupremeTech! SupremeTech specializes in bridging the divide between online and offline commerce for major retail corporations globally. Contact us for your own solutions!

            25/03/2024

            83

            Knowledge

            +0

              25/03/2024

              83

              Seamless Retail Bliss: Online-to-Offline Retail with Reserve Online, Pay In-Store

              Swift vs react native for mobile app development

              Knowledge

              +0

                Swift vs React Native for Mobile App Development in 2024

                Hi tech fellows, welcome back to SupremeTech blog. It's been a long holiday for us here in Viet Nam. But we are back, so here we go. When it comes to mobile app development, what language comes to your mind immediately? I believe two giants stand tall: Swift and React Native. But which one should you choose? Let's break it down without the tech jargon. Swift vs React Native: The origins Swift, born from the Apple family, speaks the language of iOS like a native. It's fast, it's sleek, and it's all about that iOS love. It boasts of native performance, modern syntax, and seamless integration with Apple's ecosystem. But React Native? It's the rebel with a cause, using JavaScript to bring harmony between iOS and Android. It bridges the gap between iOS and Android, offering flexibility and efficiency in development. Performance: Native vs Cross-platform When it comes to speed, Swift takes the cake. It's like a racing car, zooming ahead with native performance. Swift enjoys the advantage of native performance, thanks to its direct compilation to machine code. This results in snappy, responsive apps that align closely with iOS standards. React Native, while not inherently native, has made significant strides in optimizing performance. Techniques like Just-In-Time (JIT) compilation and native code modules contribute to smoother user experiences, albeit with a slight compromise compared to Swift in certain scenarios. Development Time and Efficiency Regarding development time, React Native emerges as the frontrunner. Its cross-platform nature allows developers to write code once and deploy it across multiple platforms, significantly reducing time and effort. Swift, however, requires separate codebases for iOS and Android, potentially elongating development cycles. Nevertheless, Swift's native approach ensures precise customization and adherence to platform-specific guidelines, which might justify the additional time investment for certain projects. Community Support and Ecosystem Both Swift and React Native thrive on vibrant communities and extensive ecosystems. Swift developers benefit from Apple's backing and a growing community dedicated to enhancing the language and its ecosystem. React Native, on the other hand, taps into the vast JavaScript community, offering a plethora of libraries, tools, and resources. This robust support system fosters innovation, facilitates problem-solving, and accelerates the development process for both frameworks. UI/UX Design: Native Feel vs Cross-platform Consistency Swift shines in delivering native user experiences tailored to iOS devices. With access to native UI components and seamless integration with Apple's design principles, Swift apps exude elegance and sophistication. React Native, while capable of achieving native-like UI/UX, may exhibit slight discrepancies across platforms due to its bridge-based rendering approach. However, with careful design considerations and customization, React Native apps can deliver cohesive and visually appealing experiences on both iOS and Android. Swift vs React Native: Maintenance and Future-proofing Maintaining and updating mobile apps is an ongoing endeavor, and the choice of framework can significantly impact this process. Swift's separate codebases for iOS and Android necessitate individual maintenance efforts, potentially increasing complexity and resource allocation. React Native's single codebase streamlines maintenance tasks, allowing updates to be applied universally across platforms. This unified approach enhances agility, facilitates feature parity, and future-proofs applications against evolving technological landscapes. Integration with Native Code and Third-party Libraries Both Swift and React Native offer avenues for integrating native code and leveraging third-party libraries. Swift seamlessly interoperates with Objective-C, enabling access to a vast ecosystem of iOS libraries and frameworks. React Native provides a bridge that allows developers to incorporate platform-specific functionalities using Objective-C, Java, or Swift. This flexibility empowers developers to harness the strengths of both frameworks while capitalizing on existing libraries and resources. So, is it Swift or React Native? Despite their differences, Swift and React Native share some similarities in terms of criteria mentioned above. Ultimately, there is no one-size-fits-all solution. Whether you opt for Swift or React Native, both frameworks offer distinct advantages and cater to diverse needs within the mobile app development landscape. By weighing the factors discussed herein and aligning them with your project objectives, you can embark on a journey that leads to the realization of impactful, innovative mobile experiences. Need a consultant for your development project? SupremeTech is here to help! When it comes to mobile app development, you are in our good hand. Dive in our success case studies to learn more about us. See you in the next article!

                20/03/2024

                80

                Knowledge

                +0

                  20/03/2024

                  80

                  Swift vs React Native for Mobile App Development in 2024

                  Post banner imagePost banner image
                  Customize software background

                  Want to customize a software for your business?

                  Meet with us! Schedule a meeting with us!