Having services in React application

react api service
react injectable services
react api service class
react service class
react singleton service
react api service example
react services folder
react context

I'm coming from the angular world where I could extract logic to a service/factory and consume them in my controllers.

I'm trying to understand how can I achieve the same in a React application.

Let's say that I have a component that validates user's password input (it's strength). It's logic is pretty complex hence I don't want to write it in the component it self.

Where should I write this logic? In a store if I'm using flux? Or is there a better option?

The first answer doesn't reflect the current Container vs Presenter paradigm.

If you need to do something, like validate a password, you'd likely have a function that does it. You'd be passing that function to your reusable view as a prop.

Containers

So, the correct way to do it is to write a ValidatorContainer, which will have that function as a property, and wrap the form in it, passing the right props in to the child. When it comes to your view, your validator container wraps your view and the view consumes the containers logic.

Validation could be all done in the container's properties, but it you're using a 3rd party validator, or any simple validation service, you can use the service as a property of the container component and use it in the container's methods. I've done this for restful components and it works very well.

Providers

If there's a bit more configuration necessary, you can use a Provider/Consumer model. A provider is a high level component that wraps somewhere close to and underneath the top application object (the one you mount) and supplies a part of itself, or a property configured in the top layer, to the context API. I then set my container elements to consume the context.

The parent/child context relations don't have to be near each other, just the child has to be descended in some way. Redux stores and the React Router function in this way. I've used it to provide a root restful context for my rest containers (if I don't provide my own).

(note: the context API is marked experimental in the docs, but I don't think it is any more, considering what's using it).

//An example of a Provider component, takes a preconfigured restful.js
//object and makes it available anywhere in the application
export default class RestfulProvider extends React.Component {
	constructor(props){
		super(props);

		if(!("restful" in props)){
			throw Error("Restful service must be provided");
		}
	}

	getChildContext(){
		return {
			api: this.props.restful
		};
	}

	render() {
		return this.props.children;
	}
}

RestfulProvider.childContextTypes = {
	api: React.PropTypes.object
};

Injectable services in React - The Guild, Using React's Context API we will learn how to wrap services and make our code more The components above would work well within a React app, because If it was already perfect, they wouldn't have kept working on it on Facebook. Try React. React has been designed from the start for gradual adoption, and you can use as little or as much React as you need. Whether you want to get a taste of React, add some interactivity to a simple HTML page, or start a complex React-powered app, the links in this section will help you get started.

The issue becomes extremely simple when you realize that an Angular service is just an object which delivers a set of context-independent methods. It's just the Angular DI mechanism which makes it look more complicated. The DI is useful as it takes care of creating and maintaining instances for you but you don't really need it.

Consider a popular AJAX library named axios (which you've probably heard of):

import axios from "axios";
axios.post(...);

Doesn't it behave as a service? It provides a set of methods responsible for some specific logic and is independent from the main code.

Your example case was about creating an isolated set of methods for validating your inputs (e.g. checking the password strength). Some suggested to put these methods inside the components which for me is clearly an anti-pattern. What if the validation involves making and processing XHR backend calls or doing complex calculations? Would you mix this logic with mouse click handlers and other UI specific stuff? Nonsense. The same with the container/HOC approach. Wrapping your component just for adding a method which will check whether the value has a digit in it? Come on.

I would just create a new file named say 'ValidationService.js' and organize it as follows:

const ValidationService = {
    firstValidationMethod: function(value) {
        //inspect the value
    },

    secondValidationMethod: function(value) {
        //inspect the value
    }
};

export default ValidationService;

Then in your component:

import ValidationService from "./services/ValidationService.js";

...

//inside the component
yourInputChangeHandler(event) {

    if(!ValidationService.firstValidationMethod(event.target.value) {
        //show a validation warning
        return false;
    }
    //proceed
}

Use this service from anywhere you want. If the validation rules change you need to focus on the ValidationService.js file only.

You may need a more complicated service which depends on other services. In this case your service file may return a class constructor instead of a static object so you can create an instance of the object by yourself in the component. You may also consider implementing a simple singleton for making sure that there is always only one instance of the service object in use across the entire application.

The Unstated React Service Pattern, Now that we have our API service wrapped in module with Unstated, lets pull that into the top of our React App, inside of index.js :  A lot of front end application development companies are using React for developing applications. Deploying an application refers to making the application accessible to the world through internet. We will discuss about the various ways to deploy a React application, the platforms to deploy and test the applications.

Keep in mind that the purpose of React is to better couple things that logically should be coupled. If you're designing a complicated "validate password" method, where should it be coupled?

Well you're going to need to use it every time the user needs to input a new password. This could be on the registration screen, a "forgot password" screen, an administrator "reset password for another user" screen, etc.

But in any of those cases, it's always going to be tied to some text input field. So that's where it should be coupled.

Make a very small React component that consists solely of an input field and the associated validation logic. Input that component within all of the forms that might want to have a password input.

It's essentially the same outcome as having a service/factory for the logic, but you're coupling it directly to the input. So you now never need to tell that function where to look for it's validation input, as it is permanently tied together.

How to Create a Service-Oriented React Web-App, Turn your static single-page-app into a dynamic service-oriented web-app. Each <Service/> -component can have one or multiple  Navigating on the Azure portal from All services, to Web, to App services We want to add a new app, give it a name, subscription (should be free if you’re on a free trial, or if you already have one), resource group (create one or use existing), then click on the Create button down at the bottom of the panel.

I needed some formatting logic to be shared across multiple components and as an Angular developer also naturally leaned towards a service.

I shared the logic by putting it in a separate file

function format(input) {
    //convert input to output
    return output;
}

module.exports = {
    format: format
};

and then imported it as a module

import formatter from '../services/formatter.service';

//then in component

    render() {

        return formatter.format(this.props.data);
    }

Thinking in React – React, You'll see here that we have five components in our app. We've italicized the data each component represents. FilterableProductTable (orange): contains the  in your React components, you can stub the services to behave and return the data you want for the specific test. Tests

Same situation: Having done multiple Angular projects and moving to React, not having a simple way to provide services through DI seems like a missing piece (the particulars of the service aside).

Using context and ES7 decorators we can come close:

https://jaysoo.ca/2015/06/09/react-contexts-and-dependency-injection/

Seems these guys have taken it a step further / in a different direction:

http://blog.wolksoftware.com/dependency-injection-in-react-powered-inversifyjs

Still feels like working against the grain. Will revisit this answer in 6 months time after undertaking a major React project.

EDIT: Back 6 months later with some more React experience. Consider the nature of the logic:

  1. Is it tied (only) to UI? Move it into a component (accepted answer).
  2. Is it tied (only) to state management? Move it into a thunk.
  3. Tied to both? Move to separate file, consume in component through a selector and in thunks.

Some also reach for HOCs for reuse but for me the above covers almost all use cases. Also, consider scaling state management using ducks to keep concerns separate and state UI-centric.

A Guide to Service Workers in React.js, If you've ever tried to start your own app (create-react-app) in React for the first time, you may have noticed that a service worker class is  Since I usually deploy apps on Microsoft Azure, it was natural to deploy a shiny new frontend on an Azure Website. The CLI tool can build your React app that can be served as a simple static site since it consists only of a single html file, a single js file and a bunch of static images and style sheets.

Consuming REST APIs With React.js, Modern web applications should have responsive and friendly UIs, ensuring we can develop a simple React application consuming the REST API we Putting our functionality behind a service which exposes certain APIs  Micro services allows the decomposition of a large monolith application into smaller loosely coupled entities that can leverage each other using http protocol. It is an implementation of the SOA architecture, and allows one to be able to leverage several advantages associated with building applications using this approach.

React Has Built-In Dependency Injection, It turns out React has a dependency injection system built in JSX, and you probably already use it. For instance, this Calculator class create its own logger service, That's why, when you want to apply the dependency injection pattern, you need First, because an element can have more than one child. Services must be created in a Windows Service application project or another .NET Framework–enabled project that creates an .exe file when built and inherits from the ServiceBase class. Projects containing Windows services must have installation components for the project and its services. This can be easily accomplished from the Properties window.

Patterns for data fetching in React, The hands-on example is a simple React application with a bunch of If you want fresh data, you need to refresh the page manually or have the page custom browser development, web services for 3D distributed game  React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes. Declarative views make your code more predictable and easier to debug.

Comments
  • You could use a package and see how they are doing it - npmjs.com/package/react-password-strength-meter
  • The password strength is just an example. I'm looking for a more general best practice
  • You might have to do it server side?
  • No. Only client side logic that should not be directly in the component. The password strength checker is just an example
  • If you have many such functions you could store them in a helper file and just require it into your component file for usage. If it's a single function that is relevant solely to that component it should probably live there no matter the complexity.
  • great answer mate, you stopped me from doing stuff brainless 8) KUDOS!!
  • what is the usage for container example?
  • I'm not advocating it, but if you wanted to go down the service locator path (something similar to Angular), you could add some kind of "injector/container" provider that you resolve services from (having previously registered them).
  • React hooks comes to the rescue. With Hooks you can write reusable logic without writing a class. reactjs.org/docs/…
  • This is the way that I would do it too. I am quite surprised that this answer has so few votes for it, as this feels to be the way with least friction. If your service depends on other services, then again, it would be importing those other services via their modules. Furthermore modules are, by definition, singletons, so there is actually no further work needed to "implement it as a simple singleton" - you get that behaviour for free :)
  • +1 - Nice answer if you're only using services that provide functions. However, Angular's service are classes that are defined once, thus providing more features than just delivering functions. You can cache objects as service class parameter, for example.
  • This should be the real answer, and not the over complicated response above