Using React with GraphQL: An Apollo Review

As enterprise AI and the Internet of Things (IoT) expand, flexibility is crucial in the software development world.

Developers need tools that help them manage a shifting network of technology while creating products that are economical to maintain.

One of the newest – with a stable release in 2016 – is GraphQL. This open source tool created by Facebook has some developers calling it “the future of APIs”.

What Is GraphQL?

GraphQL is Facebook’s query language for APIs.

It’s a syntax that outlines how to request specific data, and it’s most often used by a server to load data to a client.

In simple terms, GraphQL serves as an intermediate layer between the client and a collection of data sources.

It receives requests from the client, fetches data according to its instructions, and returns what was requested by the call.

Flexibility and specificity set GraphQL apart from other options like REST APIs.

The client can ask for the data it really wants and draw only that data from multiple sources. It pulls many resources in one call, all organized by types.

What problem does GraphQL solve?

REST APIs were a huge step forward, but they have some baggage.

Much of the data pulled never gets used, wasting time and potentially slowing an application with no payoff. REST API also use multiple calls to access separate resources.

With GraphQL, the server can query data from several hard-to-connect sources from a single endpoint and deliver it in an expected format.

It’s a standardized, straightforward way to ask for exactly what is needed.

It also solves the problem of backward compatibility. With REST APIs any changes to endpoints necessitates a version change to prevent compatibility issues.

New requirements don’t necessitate a new endpoint when using GraphQL.

React + GraphQL = Apollo

Apollo Client is a small, flexible, fully-featured client often used with GraphQL.

It has integrations for many tools including Angular and React, the latter being very popular with developers right now.

Apollo has several useful advantages. It’s simple to learn and use, so bringing teams up to speed is easy.

It can be used as the root component for state management. The client gives the calls and queries answers as props.

Plus, developers can make changes and see them reflected in the UI immediately. Apollo also features a helpful client library and good developer tools.

One of the biggest operational benefits is that Apollo is incrementally adoptable. Developers can drop it into part of an existing app without having to rebuild the entire thing.

It works with any build set-up and any GraphQL server or schema, too.

Strengths of Apollo

Being able to get complex relations with a single call- plus avoiding problems with types- are major benefits.

Apollo also offers multiple filter types, can be used as state management, and removes the need to handle HTTP calls.

With Apollo subscriptions are usually implemented with WebSockets, which is an advantage over React’s competitors.

Most importantly from an operations standpoint, Apollo is easy to learn and use.

It’s painless for team members to add it to their toolkits.

Limitations of Apollo

API are still needed for authorization and security (including tokens, JSON Web Tokens, and session management).

It’s also true that Apollo can’t go as deeply as Redux does, so when building complex apps, the tools have to be combined.

Comparison

GraphQL is often compared to REST APIs, though they aren’t exactly the same thing.

REST is an API design architecture which decouples the relationship between the underlying system and the API response, much as GraphQL serves as an intermediary, but it takes a different approach.

There are multiple endpoints compared to GraphQL’s single endpoint philosophy. That adds complexity as the application scales.

REST also suffers from under – and over-fetching. Using Apollo GraphQL queries only what is needed at the time, which eliminates the problem.

Some developers like to use Relay instead of Apollo. Relay is Facebook’s open-sourced GraphQL client.

It’s heavily optimized for performance, working to reduce network traffic wherever possible. The tradeoff is that Relay is complex and hard to learn. Many find it simpler just to use.

Future Outlook

Once considered a niche technology, GraphQL is now proving its worth.

Major companies are using it in production, including Facebook, Airbnb, GitHub, and Twitter. With this much growth over just a few years, it’s a safe bet GraphQL has a long functional life ahead of it.

Wondering if GraphQL would work for your company’s next project? Set up a complimentary meeting to review your needs and find out what kind of solution we could build for you!

Request a Consultation

What’s the Point of PropTypes In React?

proptypes

PropTypes is one of React’s most useful accessories. It provides clear, enduring assertions as to the type of data a React component needs to render properly.

The tool is built-in and ready to use without wading through complicated set-up procedures.

However, some developers bypass PropTypes because of the small amount of extra up-front coding required. That has the potential to be a serious mistake. PropTypes (and the variety of similar static type checking tools) is a valuable asset for building scalable, maintainable software.

Laying the Groundwork

To explain how PropTypes works and what it brings to the table, it’s important to understand some relevant terms.

An “assertion” is a forceful, definitive statement, whether it’s about a fact or an opinion. In programming, that statement is that something specific is always true at a certain point in code execution.

Data types, which are usually referred to as types, group similar values on which common operations can be performed.

Types are a classification identifying possible values, the amount of memory allocated to save a value, and the kinds of operations and methods which can logically be used performed on them.

JavaScript has six regular types:  string, number, undefined, null, boolean, and symbol. Some have more variety than others. “String” refers to any string, for example, and “number” has a similarly wide scope.

Other types are more restricted. “Boolean” is a binary type, undefined is a default type for any undefined variables, and null indicates there is no variable declared at all.

While this sounds complex, it’s highly intuitive in practice. Given a string of numbers it’s easy to see they can be summed but not merged without changing the meaning. 2, 5, and 76 is much different than 2576.

Conversely, though a series of words can’t be summed it could be merged. “I”, “love”, and “Orlando” is easily read even when merged to “I love Orlando”.

What is Type Checking?

Types are one of the main foundations of a programming language. Errors in defining them can derail a program entirely. In fact, many execution errors in JavaScript are type errors- for instance, trying to divide by a string.

Type checking involves making runtime assertions about the correct type of data a component requires in order to render properly. It’s independent of build time type checking.

Using the previous example, type checking would catch that it’s impossible to divide “42” by “Dent” because division isn’t an operation which can be performed with a string.

Merging “Arthur” and “Dent” into “Arthur Dent” won’t cause a problem since the “merge” operation is logically allowed for strings.

The most common tools for type checking are Microsoft’s TypeScript and Facebook’s Flow. However, when working in React there’s already a low-maintenance, easy to learn tool for type checking built into the code base: PropTypes.

PropTypes validates the data types of values as they’re passed through types. It can also flag types as mandatory or set default values to reduce the workload.

The Case for Type Checking

Developers coming to JavaScript from other languages may be used to catching errors elsewhere in the process.

This is especially true with Python, where type isn’t necessarily the best description of the restrictions the developer is trying to impose on their input.

With JavaScript, though, there are three major benefits to making the time for type checking.

Technical and structural fitness

Props are necessary to pass any value to a child component. They serve as the component’s interface to get data passed down the component tree.

Without type checking (using PropTypes or some other tool) developers risk passing the wrong data types to components. This has a negative impact on the application’s performance and can lead to crashes.

On top of that, PropTypes help catch bugs by validating data types as they pass through. This is useful as an application scales and the codebase grows

Efficient teamwork

In Agile development, using PropTypes enables better coordination between teams working on different part of the same project. They serve as documentation of how a component has to be used in terms of passing props.

This helps people who use the component later know what they can and can’t do and how to use it effectively.

Practicality

Finally, using PropTypes is simply good business sense. They reduce the amount of time spent on debugging and testing.

Less time and higher developer productivity translate into lower ongoing maintenance costs for complex applications.

How PropTypes Works

Now that the value of using PropTypes has been established, it’s time to take a look at how it actually works.

PropTypes is React’s built-in type-checking tool. PropTypes is both the name for the tool and a reference to actual PropTypes, so it’s common to see it used both singularly and in plural.

In simple terms, the tool defines the type of a prop (string, number, undefined, null, boolean, or symbol). It then exports a range of validators that can be used to make sure the data received is correct.

Every time a value is passed through a prop it’s validated for type. (“Is this a number?”) When an invalid value is provided for a prop, a warning shows up in the JavaScript console to alert developers of the issue.

There are more options for specifying types and how they’re assigned, too. Developers can specify that only a single type can be passed to a component’s children.

They can also define default values for props using “defaultProps”. React set things up so that PropTypes type checking happens after default props are resolved, so type checking will also apply to those default props as well.

It’s important to note that PropTypes doesn’t throw errors. It only shows warnings in the JavaScript console, and PropType Checking is disabled in development. It’s a guide for better development, not a safety net for messy code.

Benefits of PropTypes

The biggest advantage of PropTypes is shared with other type checkers. It makes it easy to catch bugs caused by passing data in the wrong data type (like a string in a Boolean space).

PropTypes has an edge in that it is already built into React. It’s ready to use with a very gentle learning curve. Anyone that uses the component down the road can find all available props, including their desired data type, in one place.

Some code editors support code completion for props, so it’s possible to see the available props while typing in the component in a tooltip.

What Else Is Out There?

As mentioned earlier, the two most common alternatives to PropTypes are TypeScript and Flow.

TypeScript

A strongly typed superset of JavaScript created and maintained by Microsoft. It’s dominant in the Angular community but also used outside it, for example in React.

TypeScript has a larger community and it a more established and proven product. Users find it faster than Flow. As an additional edge, TypeScript is both a type checker and a transpiler that produces pure JavaScript.

Flow requires Babel or something similar to remove type annotations.

Flow

A static type checker from Facebook, which also maintains React. Because both fall under the same owner Flow is well-tailored to play well with React, with easy integration & automated refactoring.

Though it’s intuitive and efficient for use in building React and ReactNative applications, Flow has some drawbacks. Many in the community have commented on its weak documentation.

Also, it’s impossible to ignore type errors that come from components outside the developer’s control (like Node modules). New mistakes might get lost in the flood of old type errors passed down from those external components, and there’s no way to hide those alerts or shift them to another list.

Flow is a newer tool, which comes with its own suit of benefits and limitations. Facebook is constantly working out problems and experimenting with new functionalities.

The resulting frequent, sometimes extreme version changes can be hard for developers to manage.

In practice, the best solution is a combination of tools. There’s no downside to integrating PropTypes into the development process, even if Flow or TypeScript is also being used.

It doesn’t take much time to configure and saves a lot more in terms of maintenance, quality control, and developer frustration.

Final Thoughts

Static type analysis (another term for type checking) is a highly practical way to reduce technical debt. It lends itself to the creation of a codebase which is easier to work with, has fewer bugs, and supports Agile development methods.

Using type-checking to avoid errors does extend the working lifespan of a component, too. Developers tend to prefer better documentation and clarity of requirements, and they’re more likely to reuse components that are simple to understand.

From a business standpoint, PropTypes should be an easy sell. It’s simple to set up, intuitive to use, and adds an extra layer of automated quality control.

In short, unless there’s a compelling reason not to, take the time to set up PropTypes whenever using React or React Native. The potential benefits far outweigh the minimal set-up time.

At Concepta, our clients’ business goals are also ours. Building quality software with a long working life – in part by using tools like PropTypes – is just one way we work to protect your technology investment. Set up a free, no obligation meeting to talk about where your company is going and how Concepta can get you there faster!

Request a Consultation

Choosing a JavaScript Library for Web Apps: Vue.js [REVIEW]

vuejs-review
Vue.js is a lightweight JavaScript library that focuses on the view layer of user interfaces. A JavaScript library is a collection of functions pre-written in JavaScript that can be used instead of writing code from scratch for common functions. Here is a review of Vue.js and what makes it ideal for web development.

What problem does Vue.js solve?

Using a JavaScript library like Vue.js cuts the amount of code developers need to write. Vue specifically can be used to add interactivity to existing websites.

Benefits of Vue.js

  • Real time state management
  • Virtual DOM
  • Reactive/composable view components
  • Two-way data binding
  • Transition effects system

Strengths

Vue is only the interface layer. It can be used as a feature within a page rather than building a complete Single Page Application (SPA). Also, it can be dropped into an existing project to add a degree of interactivity. New Vue.js are often surprised by how easy it is to learn. Vue is close to ordinary JavaScript, so those with a grasp of JS can pick it up almost immediately. Programmers spend less than half an hour studying it before being able to code something simple. That simplicity extends to building and troubleshooting, as well. Large frameworks impose their own form of order on developers, but Vue has few opinions of its own. Programmers are free to approach challenges in their own way. There are a wide variety of options for adding templates definition libraries. A lot of JavaScript goes into an app, which leads to slower load times. Vue has a work around for this problem through an async components feature, resulting in “lazy loading” where components are only loaded upon request. This provides high performance on older browsers or in low signal areas.

Weaknesses

Though many people compare Vue to Angular, Vue is a library and not a full framework. It primarily addresses the view layer. As a default it doesn’t come with necessary features such as a router. Creating fast, flexible SPAs with Vue.js is possible, but only in tandem with supporting libraries. The developer community for Vue is still quite small. As a result there aren’t many stable components, and neophyte Vue users may have trouble telling which version of Vue a particular library was built for. This problem should gradually diminish as Vue’s popularity grows. Unlike Angular, which is maintained by Google, Vue has a single creator in Evan You. Many of the plug-ins are written in his native language of Chinese. There aren’t many examples of Vue’s scalability. It’s possible to write large-scale apps with Vue.js, but having so few examples of scalability can be a concern for some users.

How does it compare to React, Polymer, or Angular?

React: Vue employs a virtual DOM like React and is also a view layer library. However, Vue has a gentler learning curve than React. Polymer: Vue’s components are very much like Polymer’s custom elements. The biggest difference is that because Polymer, unlike Vue, is based on Web Components. Many browsers aren’t yet compatible with Web Components, so Polymer requires polyfills to adapt to those browsers. Angular: Both Angular and Vue share two-way data binding capabilities. The programs interact well with each other, too. View is a simpler tool for less complex projects that don’t require the full power of Angular.

Real-life application

GitLab incorporated Vue.js into its front end towards the end of 2016. Frontend lead Jacob Schatz describes Vue as having “the perfect balance of what it will do for you and what you need to do yourself”. Reddit News, a browser extension that displays updates and new posts from Reddit, was built using Vue as were applications like Expedia, Alibaba, Baidu, Nintendo, and Facebook Newsfeed.

Conclusion

For simple projects that call for high performance, interactivity, and ease of maintenance, Vue.js can be a better fit than more robust full frameworks.

If you need highly experienced front-end developers who know Vue.js, share with us your challenges and we’ll help come up with the right solution tailored to fit your needs. Request a Consultation

How Does ReactJS Solve the Problem of Data Changing Over Time?

reactjs
In the five years since React was introduced by Facebook developers, more and more industry players such as Netflix, Yahoo and Atlassian are using it. What these enterprises have in common is a need to handle vast amounts of data that changes over time, especially when a company’s value proposition depends on flawless handling of streaming video.

How Does ReactJS Work?

First of all, it’s important to understand the differences between the new React Native framework and the original React.js library. The original React.js was created as a JavaScript library, primarily as a front-end interface that ran on your server. React creates composable user interfaces with reusable components that react to data changes. Instead of working with templates or HTML directives, React components call a render method that produces a string of markup, then injects this directly into your document. Whenever the data changes, React calls a new render method. As it grew, it expanded capabilities for building full web applications. Creative programmers discovered how React.js solves problems of better handling of dynamic data for faster response times. It lets you design simple views for every application state. React.js, as its name implies, responds to data changes instantly and renders the right components for a smooth user experience.

How Does React Native Work?

Initially, problem-solving with React.js was limited because it’s not a full mobile framework. In response, React Native was released in 2015. React Native compiles to native app components so you can build your apps in native iOS or native Android. It’s committed to the “learn once, write anywhere” model, although you have to come in with some app-building experience. In addition to having strong JavaScript knowledge, you should have experience developing wrappers for native components and APIs in the target natural language. Of course, you can still use React.js for building out these components because React Native implements React.js behind the scenes.

What Does React.js Solve Other Than X-Platform?

Netflix programmers explained why they chose React early last year. The problem was that users, particularly those on mobile platforms, tend to have variability in their networks. Latency and slow load times were causing users to bounce, even though Netflix didn’t have any control over the networks they used. Users needed a faster way to download and process initial markup, scripts and style sheets as data streams changed. On top of network latency, the app startup performance was slowed down by DOM elements based on the parsed JSON payloads. What attracted Netflix to React.js was the way it handled customized user interactions and rendered code for A/B testing of its streaming services. Netflix saw huge improvements in the initial load time of its applications, the performance during runtime and rapid scalability of new apps. React.js delivered isomorphic JavaScript (on both the server and the client), virtual DOM rendering with a diff algorithm and support for compositional design patterns using Mixin APIs to deal with frequent changes in the data.

Where Can You Go to Learn More?

Here’s a great React.js tutorial directly from Facebook developers, with a link to source code on GitHub. One thing you can be sure of is that your apps will have to handle more data, from more sources and in tighter refresh cycles. You should get ahead of the curve now to avoid server overloads and downtime from the flood of data coming to an app near you, sooner than you think.

If you’re looking for someone to build an app for you or if you still have questions, contact our team at Concepta and we’ll be able to help.

Request a Consultation