MVP App Development: A useful guide for start-ups (part 1)

mvp-software-development

MVP development is a great beginning point for a software project (Minimum Viable Product Development).

Examples of minimum viable products from successful businesses such as Zappos, Dropbox, and Twitter corroborate the aforementioned viewpoint. In terms of MVP software development, MVP app development, and MVP website development, the MVP idea is not new.

However, there is a lot of misunderstanding about the MVP approach and how to use it effectively. Therefore, this article will walk you through the ultimate guideline to develop an MVP app for start-ups.

This part of the guideline will help you understand more about MVP development and what to prepare. Let’s get started!

MVP definition

MVP (Minimum Viable Product) is a product having enough functionality to attract early users and validate a product concept early in the product development cycle. For example, Apple has the beta version of the newest IOS update so developers can try and give feedback. 

MVP App Development, on the other hand, is the process of creating a new product or website with enough functionality to satisfy early adopters. Only after collecting input from the product’s first consumers is the final, full set of features will be developed and released.

In another life aspect, MVP is analogous to a pilot’s flight simulator. While pilots are not required to fly planes (yet), they are expected to learn the abilities. These abilities must guarantee that the aircraft functions properly before it is released into the wild. Thus, developing a minimum viable product is analogous to going through the preflight skills checklist that is completed before the pilot’s first flight.

So you might understand the concept of MVP App Development. The next part will point out why you need it and how it will be beneficial for new start-ups. 

Why do start-ups need to build MVP?

The goal of creating an MVP is to rapidly launch a product based on your concept on a minimal budget. This method enables you to get customer input on the main product and incorporate it into future updates. An MVP can help you identify the appropriate audience, draw ideas based on experience, and save time.

MVP enables you to promote the idea without investing a lot of money or effort. It may be a great way for entrepreneurs to put their ideas to the test. You may also utilize the MVP approach when adding a new feature, even if the project is lengthy and complicated.

As a result, beginning with MVP development reduces risks and provides many advantages, as listed below:

  • Get the app into the hands of consumers straight away and get early feedback. Is it as simple to use as it appears? What features will be included in the next release? What should be dropped from the product backlog? By providing consumers with something to experiment with, you improve the likelihood of receiving honest feedback. From these inputs, you will fix the problem with the products, improve user experiences. Then you can also define the potential segment, who is attracted by your MVP. 
  • Examine the technological feasibility. You don’t need to create a full-fledged program to test implementation complexity, scalability, and possible requirements for uncommon talents. This, in turn, will assist you in progressively developing a reliable, functional product version that adds value from the outset and no room for error.
  • Present the concept to investors in order to get seed funding and assistance. To improve your chances of success, make sure you can back up your MVP with an early business plan and a marketing strategy.
  • Add new features gradually and update on a regular basis. MVP is an iterative process of improvement, therefore ensure that you are using the MVP Agile development approach. When vying for market share with large companies, the flexibility of Agile is the primary edge that early-stage entrepreneurs can depend on.

New/small entrepreneurs should consider MVP app development as a major method to build business strategies since its advantages are mentioned before and it is not easy to understand the market in the first place within a short budget. 

However, building an MVP app is not an easy task to achieve, especially with start-ups. These businesses may get some problems such as:

  • Can not distinguish the differences between final product and MVP
  • Ignore user feedbacks
  • Exceed their hypothesis
  • Over testing

In fact, working with an experienced MVP outsourcing team may help you save money and launch faster than trying to iron out the bugs on your own. When you work with JSLancer, with a professional consulting team, we will provide the most suitable solution for MVP App Development without any mentioned problems. 

Although outsourcing may contain risks that lead to time and cost consumption, you can take a look at our guide to find the right software outsourcing to eliminate the threats for a successful MVP App Development. 

In general, the right outsourcing team for your MVP development should be the one that you can communicate well with. Therefore, they will listen, understand your ideal MVP apps, and consult you on the most suitable business plan to work.

Moreover, it will become useless if you do not have a plan and objectives for the whole journey. Hence, the next part would show you how to prepare.

3 tips to prepare for MVP building

Prepare resources to conduct market research

mvp-app-development

The MVP will be the basic version of the product that you launch, with the option to enhance it as required. Prior market research will assist you in determining the feasibility of your new product or service before you begin development.

During this phase, utilize surveys, product testing, focus groups, and other methods to learn more about your target client base. Unfortunately, some concepts just do not suit the market’s requirements. In reality, more than 40% of startup failures are due to a lack of genuine product demand.

Preparing for research requires businesses to plan for further scenarios of the project or campaign. Therefore, if this part is done by carefully measuring and distributing resources, the results will come out effectively. 

For start-ups, we would recommend using available materials or secondary research to save more cost. Some useful resources for market research you should take a look at: 

  • Government resources
  • Industry summaries
  • Business location market research tools
  • Survey tools
  • Market trends

Define the right data to measure

When creating an MVP, you base it on the features you believe are most essential to your consumers. As soon as it hits the market, you’ll be able to see whether you’ve remained on track with these objectives. It’s all about what your users think at this stage. It is now your responsibility to gather “actual data” once you launch your MVP in order to determine whether or not your product was successful and how it can be improved. Here are several metrics to consider in order to get this insight:

  • Word of mouth (i.e. traffic)
  • Engagement
  • Sign-ups
  • Downloads, launch rates, etc.
  • Percentage of active users
  • Client Acquisition Cost (CAC)
  • Number of Paying Users
  • Client Lifetime Value (CLV)
  • Churn Rate

Don’t make these mistakes

The following are the essential aspects of MVP development that you should be aware of in order to avoid failure.

  • Market research should be ignored. One of the primary causes of all failures is a lack of market knowledge. Almost half of all businesses fail because their product concepts are not novel and there are many comparable services on the market.
  • Overload Features. If you bring too much with you, it will be more difficult for you to progress and reach the top. Perfectionism is admirable, yet striving for perfection may be costly. The primary goal of an MVP is to test the concept before going forward with full production.
  • Misinterpretation of Qualitative and Quantitative Feedback. Although getting a lot of input may seem to be a benefit when you’re just starting out, you must be selective about who you get it from and what you apply at the MVP stage.

Conclusion

MVP development is an essential step to take when you need to verify a product idea fast and with the least amount of cost. We hope that via this article you will understand more about MVP development and what to prepare. Then in the next part will show you steps to guarantee that your design project follows the appropriate user-centric approach and that you get the important information required to create a long-term successful solution.

Top risks of Software Outsourcing and How to mitigate them

jslancer-Top risks of Software Outsourcing and How to mitigate them

The conventional justifications for outsourcing offshore software development are also evolving over time. A few years ago, businesses mostly selected software outsourcing to decrease the cost of software development. However, as the globe becomes more open, the factors driving companies to outsource change.

As someone who has never outsourced before, you may be concerned that remote collaboration would cost you too much time and money. These concerns are understandable when the development team has yet to gain your confidence. Although it is impossible to eliminate all hazards associated with outsourcing, the majority of them are easily mitigated.

This post will highlight the top dangers associated with software outsourcing and how to minimize them.

Why software outsourcing?

Outsourcing is similar to task delegation. Companies need it since certain jobs have a high learning curve and, if not completed correctly, may result in a lot of trouble for their company. And, if the current in-house team is already overburdened, recruiting specialists in the area is both costly and time-consuming.

IT outsourcing allows companies to concentrate on the key components and procedures that they excel in. Concentrate on your abilities and delegate the rest. However, like with any other choice in our world, outsourcing software development has dangers!

However, in the vast majority of instances, stakeholders believe that outsourcing is in their best interests, with 78 percent of companies seeing their outsourcing partnerships favorably.

So why software outsourcing is risky when there are a lot of benefits? Well, everything has its limitation, there will be some problems. The next part will tell you the top risks.

Unrealistic expectations

It is not unreasonable to anticipate outstanding results. But don’t be a daydreamer. Your job should be done in tandem with your abilities and resources.

For example, a guy told an IT agency that he wanted to change the world. He aims to create a better version of Facebook’s social media platform. And he has a budget of $1000.

So, see what occurred there – this is implausible. If someone agrees to create this innovative software for $1,000, catastrophe is written all over it!

Unrealistic expectations are a major impediment to software development outsourcing success. We are often requested as software businesses to provide time and cost estimates without any previous discussion or assessment. In such a scenario, we have no clue what the whole image is.

You can’t expect an architect to tell you how much your home will cost unless you give him precise requirements, can you? So, why should you have the same expectations of a software development firm?

As I previously said, there is always someone who would nod in agreement to a $1,000 Facebook app creation. And it is here that you take a risk, even before your project begins.

If your budget does not allow for all of the features you want, split it into stages. This will save your software development expenses while also ensuring that your outsourcing runs smoothly. You can go through this process to balance it: 

  • Make a thorough list of all the features you want to include in your software program.
  • Please share this with prospective software suppliers.
  • Allow them to contact you with any questions or concerns they may have (I’m sure a competent software company will have many).
  • Sit down with them and go through every detail of this project with them, leaving no room for misunderstanding.
  • Proceed with the development after you and your partner have reached an agreement on what to accomplish.

Working with a comprehensive software outsourcing company will help you reduce the risk and better define the goal. A professional team will handle difficult problems and provide the best solution for your product, enabling you to concentrate on strategy, company development, and user growth without worry.

Communication and management

 

Even if you cope with the expectations and begin working, there will be more issues. Projects for major brands may also fail if the project lacks pace. Poor communication and missed deadlines may stymie a project to the point that it is no longer useful or relevant.

You expect a project manager to handle this when you outsource software development. Your project manager should be your go-to person for any and all issues. It is the project manager’s duty to provide the team precise instructions. They are in charge of assigning tasks and resources, monitoring overall project progress, and disseminating pertinent information to customers.

Modern and intuitive project managers will offer frequent real-time updates on the project’s status. The most essential qualities of a successful project manager are leadership, communication, and technical competence. A project manager is the project’s skeleton. He or she is essential to the project’s success or failure. Poor leadership and communication may have a negative impact on outsourcing.

To mitigate this problem, you should:

  • Understand your team. When it comes to trust and communication, a small team offers many benefits. When your software business is tiny, you have direct one-on-one interaction with CXOs such as the CEO or CTO.
  • Hold frequent meetings to keep track of the project’s development. Make sure that your selected communication methods are functional and not a nuisance with needless automatic interruptions in the world of iterative development, multinational teams, and various time zones.
  • If your project is split into milestones, demand will be updated after each one. Binaryfolks offers video updates once each milestone is completed so that the customer may witness firsthand what has been created and contact us if they have any concerns.

Moreover, you also need to ascertain that the IT services provider has a well-defined requirements collecting process in place and employs experienced business analysts. By ensuring this, the next problem will be less serious. 

Quality of Software

Everything revolves on the quality of your program. Everything you’ve worked so hard for is the software’s quality. In the event of a software malfunction, it may have a major effect on your company, beginning with a delay in project launch since engineers will need to go back and work on your software to repair those problems. If the flaws are found after the product has been released, you may suffer a significant damage to your image and may not survive long in the market.

To avoid this issue, you should: 

  • Test extensively and early. This will aid in the detection of bugs and make them simpler to deal with. Testing towards the end of the process and finding problems implies having to redo a large portion of your work as well as any future processes that rely on it. Bugs may appear at any point, but frequent testing makes it more cost-effective to address them sooner rather than later.
  • Conduct a comprehensive code review to ensure that it has quality code in place. The code must be straightforward and uncomplicated.

Unforeseen expenses

When you outsource for the first time, it’s normal to be concerned about unforeseen expenses that may emerge throughout the development process. Although most costs are obvious at the start of the collaboration, others may be concealed from your view.

Three stages to reduce the unforeseen expenses:

  • Before you begin working together, make sure you have a clear set of expectations (alternatively, organize a requirements gathering workshop). This will assist you in defining the scope of work and reducing the possibility of unforeseen expenses.
  • Learn about the price models provided by the supplier. Different businesses may have different ideas about fixed and non-fixed pricing contracts. Select the engagement model that is most suited to your project.
  • Sign a Service Level Agreement (SLA) outlining the services and prices offered by the web development outsourcing firm. Check for any hidden expenses, such as integrations, hosting, on-site visits, working overtime, and purchasing the required plug-ins/hardware/software.

More than ever, you should have a backup plan for this before signing the contract. Working with a consultant of the team carefully is also a good idea to measure and better deal with this.

Ever-changing requirement spec

The issue arises when development is proceeding apace. Customers, on the other hand, were wondering whether they could possibly implement a whole new authorization access control and discard the one that had previously been established. It’s not working for us!

There are two issues with this: First and foremost, you spent a significant amount of money for a critical feature that you want to totally demolish. And you’ll have to spend a lot more to redevelop it. Second, this will substantially lengthen the development time.

Keep in mind that your software engineers are not Superman! They just have two hands, and that is all they have to offer you.

The risks of altering software requirements are that you will go back and forth a lot, which will slow down the whole process. Estimates, both in terms of cost and time, will skyrocket, and the project’s chances of success will begin to dwindle.

The most useful solution for this are: 

  • Conduct market research on the characteristics you need for your application. Examine which characteristics are needed and which are not.
  • Before deciding on the main features, make sure you discuss the whole user path and user engagement with your software provider.
  • Create an MVP. Run it by your users.

Conclusion

Most outsourcing risks may be mitigated with adequate planning. Following the suggestions above may help you save a lot of time and money on software outsourcing.

Trusting an external team with the right skill set to develop a high-value product for consumers has great potential to pay dividends. It is now simpler than ever to locate third-party experts ready to work on a project-by-project basis — and every business should take advantage of this sooner rather than later.

4 Steps to Find The Right Software Outsourcing Company for Your Project

4-steps-to-find-software-outsourcing-company

When a company chooses to have specific software solutions created by a third party, this is referred to as software outsourcing. Outsourcing software development offers many benefits, including cost savings, increased productivity, reduced risk, and better security.

Hiring a software development firm may be a difficult process, but it doesn’t have to be. 

This post will provide you with “4 Steps to Find The Right Software Outsourcing Company for Your Project”. It doesn’t matter whether you’ve already decided to outsource or not—you may utilize this list to find suppliers of virtually any kind. So keep reading to make an informed choice regarding your company.

These 4 steps are:

  • Step 1: Define software outsourcing landscape
  • Step 2: Framing and scoping your project
  • Step 3: Researching and contacting software development company
  • Step 4: Selecting, negotiating and contracting

Step 1: Define software outsourcing landscape

It is critical to understand the many kinds of software outsourcing firms that exist. When you fully understand what is available, you will make a good choice. 

Depending on a number of criteria, each kind of software agency may be a suitable match; and have a significant effect on the project’s delivery and quality. There are 3 common types of software outsourcing for SMEs such as: 

  • Onshore software outsourcing company
  • Offshore software outsourcing company
  • Nearshore software outsourcing company

Onshore Software Outsourcing Company

When a firm outsources work to a company in the same nation, this is referred to as onshore software development. For example, a company in New York may need the services of a mobile app developer and opt to outsource the job to a company in Boston that specializes in that sector.

For companies, onshore outsourcing is the most geographically convenient choice. Companies that are under-resourced or overburdened with work often outsource to onshore developers for ease. It frees up corporate time to concentrate on day-to-day operations and may assist in guaranteeing that goods are delivered on time.

However, even geographical benefits are obvious, from an hourly cost perspective, onshore companies will be more expensive. You can estimate onshore rates to be approximately three times more expensive than offshore/nearshore resources. As an SME, this solution can be a burden on your budget. Moreover, with the current technology development to communicate, you would find other alternatives from outside the border. 

Offshore Software Outsourcing Company 

Offshore software development entails outsourcing work to a third party in a geographically distant area from the host nation. For example, a company in the United States may outsource to an offshore software outsourcing team in Vietnam.

Companies have always outsourced to take advantage of cost-saving. However, recent trends indicate that businesses are becoming more concerned about quality.

One of the primary advantages of offshore software development is that it gives businesses access to a bigger talent pool of developers that would otherwise be unavailable to nearshore and onshore enterprises. Businesses are not limited by the abilities of their immediate workforce.

Offshore development may be beneficial for projects with limited finances or that need specialized knowledge that is difficult to obtain. In addition, this is also a chance to explore new markets and expand your business. As an offshore team work internationally, they would provide multiple solutions that satisfy different cultures and insights. 

Nearshore software outsourcing company

When a business outsources work to a nearby nation that is geographically close to its own, this is referred to as nearshore software development. Many US businesses, for example, outsource software development to Latin America, where nations such as Colombia, Mexico, and Argentina have work hours that are consistent with US time zones.

Nearshore development allows businesses to efficiently expand their teams by providing quick access to software developers in the same time zone. Nearshore businesses often have comparable linguistic and cultural characteristics, resulting in a fruitful working partnership.

Cultural compatibility helps ensure that developers understand the project’s fundamental concepts, reducing the chance of misunderstanding.

Once you know your options, it’s time to point out the needs of your project. Clear requirements and expectations will save more time and money to figure out the right software outsourcing company.

Step 2: Framing and scoping your project

When choosing a software outsourcing company, it is critical to scope the project.

Imagine telling a waitress you want something savory and receiving a sweet meal. Some people may like it in a restaurant environment, but not so much when it comes to software.

Spending time deciding what you want to purchase can only benefit you in the long run. The more preparation work done ahead of time, the more accurate the estimate and expectations from the software development firm will be.

Budget Backwards versus Feature Forward

Every software project has three variables: budget, scope, and schedule. As a result, we have two main kinds of projects that define a product’s lifetime.

Most projects fall somewhere in the center of these two methods, but it’s critical to determine which variable is known and which is the greatest priority in order to fill out the remainder of the equation.

  • Budget/Timeline Backwards: These projects have maximum money or strict delivery timeline, and the project team works backward to determine what can be completed in the time or budget allowed. In order to stay under budget or on schedule, these projects often compromise features or quality.
  • Feature Forward: These projects concentrate on the scope and work backward to establish a schedule and budget depending on the scope and features needed. It is okay to spend more in order to launch the desired scope, and the team is ready to pay more in order to get more.

Going from feature list to final product

We’ll go through a commonly utilized software development method. When contacting a software development firm, it is critical to understand where you are in the process so that you can choose the best possible partner.

It consists of many stages, each of which is described below. As you go through these steps, you will know the needs of the project and it is able to observe and ready for the next steps.

  1. Software Strategy (also known as “Discovery”)
  2. List of Prioritized Features
  3. Designs having Technical Requirements that have been annotated
  4. Advancement (Sprint Plan)
  5. Launch Feature Enhancement (Repeat Steps 1-5)

How much is it going to cost?

Without a basic framework, it is impossible for an agency to estimate the cost of a software project, which is why it is critical to specify the scope of your project.

Consider the following scenario: you want to know how much it would cost to construct a bespoke house but don’t know how many bedrooms you need. What about the restrooms? Should I tell one or two stories? Is it a renovation or new construction?

As you are aware, knowing your project is critical. After you’ve nailed down a few key factors, deciding which kind of company to employ becomes a lot simpler.

The ‘Magic Triangle’ is a useful graphic when discussing cost. According to theory, you can’t extend one side of the triangle without impacting the other two. Time, money, and scope are not mutually incompatible concepts.

Clearbridge Mobile’s Project Management Triangle.

The following are critical questions for every project:

  • How much money do you have?
  • Is it feasible for the scope we desire?

In summary, a professionally developed app would typically take 4-6 months to complete and will cost between $150,000 and $550,000, depending on complexity.

Variables affect the pricing. If you understand the factors, you will be a lot less startled if a quotation or timeframe changes.

For young businesses, offshore outsourcing would be the best solution for budget problems. You can find outsourcing with high-quality, up-to-date technologies and innovative solutions but still unsure the professional works within your budget. When compared to India and China, outsourcing software development to Vietnam may save up to 50% on operational costs. According to CIO Magazine, this may save up to 90% in expenses when compared to the US.

Step 3: Researching and contacting software development company

When looking for a software outsourcing company, it’s useful to know what to look for. Signing a contract indicates that you are purchasing something from them and have faith in what they are offering. We wish there was a quick solution, but if you’ve never worked with a reputable company, you’ll need to do your homework, ask for references, and study reviews.

You should go through 4 stages: 

  • Creating an initial list of software development companies
  • Initial company assessment
  • Creating a short(er) list
  • Contacting each software development company

Step 4: Selecting, negotiating, and contracting

You understand the terrain, you’ve scoped your project, you have a budget and schedule in mind, and you’ve identified a few prospective partners.

How do you choose one?

This may be particularly difficult if you like all of your choices. Plan to finish the decision-making process in less than a month.

There is no one criterion that will identify the best applicant. However, there are certainly good indicators and concepts you may use to assist make the choice a little easier.

Evaluating proposals/partners

You want to have a few choices. Examine the agency landscape and try to comprehend the distinctions between proposals. Large pricing disparities indicate a lack of understanding of the project’s scope.

Alternatively, a business may propose to provide much less than you would anticipate.

Always be truthful with the firm – “We are talking with X businesses, here is what we like about each company, and this is how we will make our choice.”

Explain who they are competing against and what the advantages and disadvantages of these relationships are. This may assist to clear up any confusion about deliverables.

The company’s salespeople maybe your greatest buddy and a strong negotiator for you. A software project’s terms are not necessarily hard and fast. Count on the sales team to come up with innovative ideas that benefit both parties.

Contracts and negotiations 

You will be required to sign a contract or a series of contracts. The contracts you will most likely be required to sign are listed here. We’ve attempted to summarize the essential elements and supplied the contracts we use as references.

  • Confidentiality Agreement (NDA)
  • Masters Services Agreement (MSA)
  • Statement of Work (SOW)

Conclusion

How well your future application or software performs is determined by the competence and experience of the software development firm that creates it.

We hope that these “4 Steps to Find The Right Software Outsourcing Company for Your Project” would help you find a suitable solution for your project. Choosing the appropriate agency is thus critical to accomplishing your business objectives and ensuring that your consumers receive a bug-free, highly performant, and useful piece of technology.

Never code alone, introduce Copilot

The Alpha version of Github Copilot is released recently, and it made a bang on HN. As a huge fan of Github and code completion, I am eager to see what can help me code faster.

From day one, it makes me really excited. Believe me or not, I think it is the best code completion tool at this time.

What is Github Copilot, and how does it help us?

GitHub Copilot is a product of the partnership between Microsoft and OpenAI company.

OpenAI is already a famous AI and machine learning company; they are the author of DeepMind – the famous AI engine that beats several competitive StartCraft 2 and Dota 2 players!

“OpenAI Codex was trained on publicly available source code and natural language, so it understands both programming and human languages.”

copilot.github.com

Copilot collects data from the open-source repositories on GitHub or public forums. It can read what you are writing in the code editor, like a variable name, an uncompleted function, and then the AI will bring some solutions to complete what you are doing faster. As a result, you will save a lot of time looking, which means code faster, less work, and more productivity for us.

How good are the suggestions?

First example

Let’s get started with some simple functions to see how good are those suggestions. Suppose that you are creating a signup form, and you are going to write some input validation functions. So I make a file called validationHelper.ts and write a function to validate an email address.

Let’s write the first line.

export default function validateEmail(input: string) {

And then I wait for 3 secs, it shows a suggestion, and I just need to press the “tab” or “enter” to apply this suggestion to my code.

The suggested regex pattern is correct. It is also tested against my variable name “input,” which is exactly what I want.

I also write another function: validateWebsite, and it also works well. It also suggests a function: validatePhoneNumber. Is this a mind reader?

Second example

Trigger file download in the browser is a reasonably common frontend task. We usually create a hyperlink element, set the href to the download URL, insert the element into the document, and then simulate clicking on that element.

The first suggestion is not really what I want because the hyperlink element is not removed from the document after the downloading has been triggered. Fortunately, Copilot can provide some other suggestions if the first of suggestions doesn’t match your goal.

It looks great! Honestly, although I am a senior developer, I always find myself on Google to find these snippets.

Third example: Create Login Form

Let’s create a login form using react-hook-form. This is my favorite form library due to its popularity, ease of use, and performance.

So I started by writing these 2 lines:

import { useForm } from 'react-hook-form

export default function LoginForm() {

This time, the suggestions are NOT correct anymore since Copilot fails to recognize the react-hook-form and shows hints of formik instead. So I cannot use any of these suggestions.

Maybe in the future version, Copilot should evaluate the coding context better.

Conclusion

Currently, GitHub Copilot supports five languages such as Python, TypeScript, JavaScript, Ruby, and Go. 

Suppose you are developing an app with one of those coding languages; you should try it right now. If not, you have to wait for a new update. As a ReactJS front-end developer, I will continue to use it as much as possible.

The commercial product of Copilot may be launched soon. I am really excited to see what they will bring in the commercial product. Right now, I hope they can improve Copilot, and it should understand our code better.

Thanks for reading, and happy coding.

Copywriter: Felix Le & David Tran

Any comments, please send to: hello@jslancer.com.

Optimize Webpack bundle size for your frontend project.

Nowadays, ReactJS and all of the SPA frameworks get a bad rap for their heavy bundle size, even for their small app.

Moreover, we are not making web-apps for desktop users, 90% traffic of our website comes from mobile devices. It’s important to reduce the bundle size for our app to make it loads.

Here are something you can do to reduce the Webpack bundle size of your app. 

Drop support for old browsers

Recently, Microsoft Team has dropped the support for IE11. There is a lot of benefits when you decide to drop support for old browsers:

  • We don’t need to convert your ES6 code to ES5 anymore. Since ES6 code tends to be shorter than ES5, your bundle size will be reduced too.
  • We don’t have to ship polyfills. Most of the polyfills are huge.

Code splitting (lazy-loading)

When Webpack bundles our code, it merges every file and module into a single huge file. Inject this bundle to HTML will load the entire of our app.

But usually, we don’t need to load the entire of our app at once. We can split it into smaller chunks, these chunks should be transferred to the user’s browser when they actually need it. Doing this will dramatically reduce our initial bundle size and user can use our app faster.

The code splitting is well documented on React team here: https://reactjs.org/docs/code-splitting.html. Personally, I think we don’t need to apply lazy loading to every single component, doing cause more harm to user experience since our users always have to wait for a millisecond to see the component. Lazy loading component by route is enough. 

Use libraries which support tree shaking

Tree shaking is a process that removes dead-code from your bundle. When you use a non-tree-shaking library, you are putting the whole library into our bundle, although you just import a small part of their library. There are some alternative libraries that support tree shaking. For example, react-window and react-virtualized do the same things and developed by the same author, but the first one is not only smaller but also supports tree-shaking. 

Other libraries that don’t support tree-shaking are lodash and momentjs.

With lodash, you should import specific method one by one

//incorrect
import lodash from 'lodash';
import { merge } from 'lodash';

//correct
import merge from 'lodash/merge';
import each from 'lodash/each';

However, if you decide to support modern browsers, you can replace lodash with ES6 implementation here: https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore

With momentjs, there are several options include dayjs, luxon, datefns. Lightbox on Google Chrome also advises us using these libraries.

Analyze your Webpack stats

Webpack provides an option to generate bundle information in a JSON file. This file gives us information on what was bundled and the size of each module. 

Since this is a JSON that is hard for us to visualize, we can use this plugin to generate a nicer HTML report chart.

Build your ideal apps with JSLancer

Why choose us? 

  • Save up to 70% of your budget and still remain the product’s quality.
  • Transparent commitments and observable plans for long-term cooperation.
  • 24/7 support team
  • 100% of software developers have +5 years of experience, high-level of tech skills and are fluent English speakers
  • Free consultation and Proposal

Contact Us Now: hello@jslancer.com

A comparison of formik, final-form and react-hook-form

Form is essential for every website on internet. Building form with ReactJS is not easy as React is just a UI library and it doesn’t provide form utility out of the box. So we have to rely on the ReactJS ecosystem to find a library to do the repetitive and hard work for us.

Choosing a library for your project is not easy as well. As an experienced ReactJS developer, you know that there are always a ton of libraries to choose from. And you have to read all of the documents and test them by yourself.

That’s why in this post, I will make a comparison of some well-known form libraries.

For handling form, we have these candidates:

NameGithub stars Weekly downloads Size
formik23.4K868K7.22 kB
final-form2.5K222K5.1 kB
react-form1.9K12K4.3 kB
react-hook-form12.5K270K8.67 kB
redux-form12.3K389K26.4 kB

That’s quite a lot for me to do the comparison, so in this post, I gonna compare formik, final-form, and react-hook-form.

There is no point to use redux-form as redux-form’s developer already replaced by final-form. Also, storing form data in Redux state is not a wise decision.


Development experience comparison

Formik

Based on the Github stars and weekly download, formik is the most well-known library for handling form. I have used formik in some projects and I have to admit it was the best library.

This is how you use formik in your component:

import React from "react";
import { Formik } from "formik";

const Basic = () => (
  <div>
    <h1>Anywhere in your app!</h1>
    <Formik
      initialValues={{ email: "", password: "" }}
      validate={(values) => {
        const errors = {};
        if (!values.email) {
          errors.email = "Required";
        } else if (
          !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
        ) {
          errors.email = "Invalid email address";
        }
        return errors;
      }}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          setSubmitting(false);
        }, 400);
      }}
    >
      {({
        values,
        errors,
        touched,
        handleChange,
        handleBlur,
        handleSubmit,
        isSubmitting,
        /* and other goodies */
      }) => (
        <form onSubmit={handleSubmit}>
          <input
            type="email"
            name="email"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.email}
          />
          {errors.email && touched.email && errors.email}
          <input
            type="password"
            name="password"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.password}
          />
          {errors.password && touched.password && errors.password}
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
        </form>
      )}
    </Formik>
  </div>
);

export default Basic;

Formik is verbose and declarative, so you have to append Formik the render result. Although the code above is easy to understand for developers but I found some disadvantages:

  • You have to render Formik in the your component, it makes the render function longer and harder to read.
  • You have to pass handleChange, handleBlur, and input value into your input element (you have to use Field component to reduce these code)
  • You have to write your own validation method or use another validation library like joi or yup.
  • Formik re-render your component at every input change.
  • Formik provides a hook function, but it doesn’t work with Field, FieldArray, or ErrorMessage.

final-form

This library is made by the author redux-form. That’s why it fixed a lot of mistakes from Redux-Form. One of the mistakes is we should avoid store form state in Redux. There is no benefit from storing your form data in Redux state before the form is submitted.

The usage of final-form is very similar to formik:

import React from "react";
import { render } from "react-dom";
import Styles from "./Styles";
import { Form, Field } from "react-final-form";

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const onSubmit = async (values) => {
  await sleep(300);
  window.alert(JSON.stringify(values, 0, 2));
};

const App = () => (
  <Styles>
    <h1>React Final Form Example</h1>
    <h2>Password / Confirm Validation</h2>
    <a
      href="https://final-form.org/react"
      target="_blank"
      rel="noopener noreferrer"
    >
      Read Docs
    </a>
    <Form
      onSubmit={onSubmit}
      validate={(values) => {
        const errors = {};
        if (!values.username) {
          errors.username = "Required";
        }
        if (!values.password) {
          errors.password = "Required";
        }
        if (!values.confirm) {
          errors.confirm = "Required";
        } else if (values.confirm !== values.password) {
          errors.confirm = "Must match";
        }
        return errors;
      }}
      render={({ handleSubmit, form, submitting, pristine, values }) => (
        <form onSubmit={handleSubmit}>
          <Field name="username">
            {({ input, meta }) => (
              <div>
                <label>Username</label>
                <input {...input} type="text" placeholder="Username" />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>
          <Field name="password">
            {({ input, meta }) => (
              <div>
                <label>Password</label>
                <input {...input} type="password" placeholder="Password" />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>
          <Field name="confirm">
            {({ input, meta }) => (
              <div>
                <label>Confirm</label>
                <input {...input} type="password" placeholder="Confirm" />
                {meta.error && meta.touched && <span>{meta.error}</span>}
              </div>
            )}
          </Field>
          <div className="buttons">
            <button type="submit" disabled={submitting}>
              Submit
            </button>
            <button
              type="button"
              onClick={form.reset}
              disabled={submitting || pristine}
            >
              Reset
            </button>
          </div>
          <pre>{JSON.stringify(values, 0, 2)}</pre>
        </form>
      )}
    />
  </Styles>
);

render(<App />, document.getElementById("root"));

As you see, we need to render the Form component, and callbacks for onSubmit, validation. You also have to use <Field> component to pass the props to your input element.

Similar to formik, final-form doesn’t provide any validation method, you have write the validation by yourself. It doesn’t support joi or yup out of the box too, you need a work-around to make it work with joi and yup (https://github.com/final-form/react-final-form/issues/116)

react-hook-form

I already like hooks because they greatly reduce the amount of code I need to write.

I found react-hook-form on /r/reactjs. At that time, I mostly write the form and handle form validation by myself, it took me a lot of time to maintain so I decided to try this library.

import React from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const { register, handleSubmit, watch, errors } = useForm();
  const onSubmit = data => console.log(data);

  console.log(watch("example")); // watch input value by passing the name of it

  return (
    {/* "handleSubmit" will validate your inputs before invoking "onSubmit" */}
    <form onSubmit={handleSubmit(onSubmit)}>
    {/* register your input into the hook by invoking the "register" function */}
      <input name="example" defaultValue="test" ref={register} />

      {/* include validation with required or other standard HTML validation rules */}
      <input name="exampleRequired" ref={register({ required: true })} />
      {/* errors will return when field validation fails  */}
      {errors.exampleRequired && <span>This field is required</span>}

      <input type="submit" />
    </form>
  );
}

My first impression with react-hook-form is the code is shorter, cleaner, and easy to understand. I just need to pass register method into my input element and the form just works.

It has some standard validation methods to help me quickly setup form validation. I can also use yup to create a schema and validate form.

Performance comparison

One of the key features of react-hook-form is it has the best performance. Actually, I never have trouble with my forms. Unless you are building a real-time data application then the overall React performance is okay for me.

But if you really about the performance then react-hook-form is the best because it reduces waste render cycle.


Conclusion

At this time of writing, react-hook-form is my favorite library for handle form. The only downside is it only works with functional component. So you can’t use it if the React version of your legacy project is smaller than 16.8.

Meanwhile, Formik is still a solid choice for you, especially if you have to work with class component.


Realize your idea with JSLancer

JSLancer is a fast-growing software development outsourcing company, with a customer-come-first approach, the firm has become a trusted technology partner for companies worldwide from the USA, UK to Australia, and Singapore. We build high-quality web applications with ReactJS, NodeJS, GraphQL, Redux.

Why choose us? 

  • Save up to 70% of your budget and still remain the product’s quality.
  • Transparent commitments and observable plans for long-term cooperation.
  • 24/7 support team
  • 100% of software developers have +5 years of experience, high-level of tech skills and are fluent English speakers
  • Free consultation and Proposal

Contact Us Now: hello@jslancer.com

How to organize your React Redux project ?

I guess the title of this post is also the most asked question of any new React developer. There is no easy answer to this question because each project will have a different technology stack and requirements. Even Dan Abramov posted this tweet:

https://twitter.com/dan_abramov/status/1027245759232651270

I have taken a screenshot of the website in the Tweet:

While this is a correct advice, it doesn’t work well for new React developers. If you are learning React by yourself and you don’t have real experience with a production-ready React project. It would take a long time before you figure a good structure that fit for your project and coding style. This is the reason why I want to share my opinion in this post 🙂

Project context

Before sharing my project structure, let me give you a little context. This structure will work for small to medium size project. By this size project, it means this project has less than 10 pages and less than 150 components. This project also:

  • Manage application state by Redux
  • Follow container and component pattern
  • Fetch and post data to the backend via Rest API
  • It uses SCSS and CSS Module for component styling.

So this is a typical React project.

Structure

There are 6 important folders in the screenshot above. They are assets, components, containers, reducers, services. I will explain the usage of each folder shortly.

Explanation

assets

This folder holds static assets for your app. They could be fonts, icon, SVG or JPEG images or any JSON file, etc. If you have too many file types, you probably want to create some subfolders to hold them.

components

This folder holds all of the components that are responsible for look and feel of your app. These components don’t fetch data by themselves but receive data and callback via props. They also don’t connect to Redux, that is the job of the containers. You probably hear about the container and component patter. Here is the famous explanation about this pattern.

If your project has a lot of pages, you can create some subfolders inside components folder. For each component, you can create a folder to store the component. For example, if you have a SearchBox component, you will create SearchBox folder. Inside of SearchBox folder, we will create 3 files: index.js, SearchBox.js and SearchBox.scss.

index.js will look like this:

export { default } from './SearchBox';

This default export statement allows you import SearchBox easier, so you don’t have to repeat “SearchBox” again in the import path.

// Ngắn gọn
import Searchbox from '../components/Employee/Searchbox';

// Dài hơn
import Searchbox from '../components/Employee/Searchbox/SearchBox';

SearchBox.js contains the implementation for SearchBox component and SearchBox.scss contains the styling for SearchBox component.

containers

This folder contains components that are connected to Redux. These components are called container. Here is an example of a container:

import { connect } from 'react-redux';
import { toggleSearchKeyword } from '../reducers/search';
import SearchBox from '../components/Header/SearchBox';

const mapStateToProps = state => ({
  keyword: state.search.keyword,
});

const mapDispatchToProps = {
  search: toggleSearchKeyword,
};

export default connect(mapStateToProps, mapDispatchToProps)(SearchBox);

reducers

You may wonder why we don’t have the redux related folders like actions, constants or selectors like any regular Redux project. In my opinion, these folders increase the complexity of our projects and when you want to change a simple feature, you have to edit many files. I found that ducks pattern is particularly helpful to organize the Redux files.

How to implement ducks pattern? Let’s take this example, you have search employee feature in your app. Instead of creating many files like: actions/employeeSearch.js, constants/employeeSearch.js and reducers/employeeSearch.js..

We only create a single file: reducers/employeeSearch.js. In this file, we include all of the action creators, constants, selectors and reducer for search employee feature.

Example:

const SET_SEARCH_EMPLOYEE_KEYWORD = 'SET_SEARCH_EMPLOYEE_KEYWORD';

export const setSearchEmployeeKeyword = keyword => ({
  type: SET_SEARCH_EMPLOYEE_KEYWORD,
  payload: keyword,
});

export default function reducers(state = '', action) {
  switch (action.type) {
    case SET_SEARCH_EMPLOYEE_KEYWORD:
      return action.payload;
    default:
      return state;
  }
}

This pattern works well in most of my project.

Notice that we don’t have any subfolder inside of reducers because we want to keep our Redux state at flat as possible. Usually, I don’t have too much data inside Redux state and I only store the application-wide data in Redux state.

services

This folder contains the API service files which helps your React app connects to the backend.

Summary

I hope this post could give you an idea on how to organize your project better. Please don’t stick to this structure, you are free to move your file until you feel it fits better for your project. Feedbacks are welcome 🙂

Build your ideal apps with JSLancer

JSLancer is a fast-growing software development outsourcing company, with a customer-come-first approach, the firm has become a trusted technology partner for companies worldwide from the USA, UK to Australia, and Singapore. Our close-knit team consists of experienced engineers who can tackle complex challenges and bring the best solution for your product, allowing you to focus on strategy, business development, and growing your user base with no worries.

Why choose us? 

  • Save up to 70% of your budget and still remain the product’s quality.
  • Transparent commitments and observable plans for long-term cooperation.
  • 24/7 support team
  • 100% of software developers have +5 years of experience, high-level of tech skills and are fluent English speakers
  • Free consultation and Proposal

Contact us now: hello@jslancer.com

Implement Tree view component with ReactJS and Styled-Components

Tree view is one of the most popular components, you can see tree view everywhere from MacOS Finder or Window File Explorer or in any code editor like VSCode, Sublime Text, etc.

Although you can quickly find a Tree View package on Github but sometimes we might want to implement Tree View by yourself because there are some limitations of 3rd packages:

  • The package doesn’t allow you to change layout and design easily.
  • There are some different requirements in our tree view.
  • The package owner doesn’t maintain it anymore so it is left with many bugs.

Here is the demo of our tree view: http://davidtran.github.io/treeview/

And this is the source code: https://github.com/davidtran/simple-treeview

Let’s start!

Create project

We will use create-react-app to create our project. It’s my favorite tool to create any React project because it is very easy to use and fit all kind of projects. Now open your terminal and run the following commands:

npm install -g create-react-app 
create-react-app react-treeview

After create-react-app has created your project, you can run project by this command:

cd react-treeview
yarn start

The website will be opened in your browser. Any changes in source code will recompile your project and also reload website.

Now we need to install the following dependencies:

styled-components: I love this library because it has many advantages over SCSS and CSS Modules:

  • It utilizes ES6 template string and SCSS syntax so you can use Javascript in your styled component thus it is easy to change CSS properties by React props.
  • It is easier to share styled component than SCSS.
  • It is easier to recognize and eliminate any unused SCSS code in styled components.

lodash: this library contains some helpful javascript functions.

react-icons: this package contains most of the popular font icons like Font Awesome, Material or Ion Icons..

props-types: it is always necessary to enforce good coding style.

yarn add styled-components lodash react-icons prop-types --save

Start coding

Let’s open your favorite text editor and implement our Tree View

We will create 2 components: Tree.js and TreeNode.js. Put these components inside src/components.

Tree.js: this component is responsible to display and manipulate tree data. It also will render TreeNode.

TreeNode.js: this component is responsible to render node content.

We start with Tree.js first.

Tree.js

Open Tree.js and import these libraries:

import React, { Component } from 'react';
import values from 'lodash/values';

Besides React and Component, we also import values which comes handy when we want to convert object into array.

Now we defined some fake data for our tree view:

const data = {
  '/root': {
    path: '/root',
    type: 'folder',
    isRoot: true,
    children: ['/root/david', '/root/jslancer'],
  },
  '/root/david': {
    path: '/root/david',
    type: 'folder',
    children: ['/root/david/readme.md'],
  },
  '/root/david/readme.md': {
    path: '/root/david/readme.md',
    type: 'file',
    content: 'Thanks for reading me me. But there is nothing here.'
  },
  '/root/jslancer': {
    path: '/root/jslancer',
    type: 'folder',
    children: ['/root/jslancer/projects', '/root/jslancer/vblogs'],
  },
  '/root/jslancer/projects': {
    path: '/root/jslancer/projects',
    type: 'folder',
    children: ['/root/jslancer/projects/treeview'],
  },
  '/root/jslancer/projects/treeview': {
    path: '/root/jslancer/projects/treeview',
    type: 'folder',
    children: [],
  },
  '/root/jslancer/vblogs': {
    path: '/root/jslancer/vblogs',
    type: 'folder',
    children: [],
  },
};

As you can see, we store tree data in an object and we don’t have any nested object.

Every node is referenced by path property. This flat data structure makes it easy to quickly take data of any node and also quickly modify data.

It’s also easier to debug tree data because we don’t have to go to any nested object to read object content.

Here is the content of Tree class:

export default class Tree extends Component {

  state = {
    nodes: data,
  };

  getRootNodes = () => {
    const { nodes } = this.state;
    return values(nodes).filter(node => node.isRoot === true);
  }

  getChildNodes = (node) => {
    const { nodes } = this.state;
    if (!node.children) return [];
    return node.children.map(path => nodes[path]);
  }  

  onToggle = (node) => {
    const { nodes } = this.state;
    nodes[node.path].isOpen = !node.isOpen;
    this.setState({ nodes });
  }

  render() {
    const rootNodes = this.getRootNodes();
    return (
      <div>
        { rootNodes.map(node => (
          <TreeNode 
            node={node}
            getChildNodes={this.getChildNodes}          
          />
        ))}
      </div>
    )
  }
}

Tree.propTypes = {
  onSelect: PropTypes.func.isRequired,
};

There are 3 methods in this object:

  • getRootNodes: this method returns top-level node in tree data (isRoot === true)
  • getChildNodes: this method reads children property from a node and map with tree data to return an array of children objects.
  • In the render methods, we find root nodes and render them.

TreeNode.js

TreeNode is the component which renders content of item on our tree view. Let’s start by import these libraries:

import React from 'react';
import { FaFile, FaFolder, FaFolderOpen, FaChevronDown, FaChevronRight } from 'react-icons/fa';
import styled from 'styled-components';
import last from 'lodash/last';
import PropTypes from 'prop-types';

Here is the implementation of TreeNode:

const getNodeLabel = (node) => last(node.path.split('/'));

const TreeNode = (props) => {
  const { node, getChildNodes, level, onToggle } = props;

  return (
    <React.Fragment>
      <div level={level} type={node.type}>
        <div onClick={() => onToggle(node)}>
          { node.type === 'folder' && (node.isOpen ? <FaChevronDown /> : <FaChevronRight />) }
        </div>
        
        <div marginRight={10}>
          { node.type === 'file' && <FaFile /> }
          { node.type === 'folder' && node.isOpen === true && <FaFolderOpen /> }
          { node.type === 'folder' && !node.isOpen && <FaFolder /> }
        </div>
        

        <span role="button">
          { getNodeLabel(node) }
        </span>
      </div>

      { node.isOpen && getChildNodes(node).map(childNode => (
        <TreeNode 
          {...props}
          node={childNode}          
          level={level + 1}
        />
      ))}
    </React.Fragment>
  );
}

TreeNode.propTypes = {
  node: PropTypes.object.isRequired,
  getChildNodes: PropTypes.func.isRequired,
  level: PropTypes.number.isRequired,
  onToggle: PropTypes.func.isRequired,  
};

TreeNode.defaultProps = {
  level: 0,
};

export default TreeNode;

First, we define getNodeLabel function. This function splits node.path and returns the last segment. Eg: /path/to/myfile.json becomes myfile.js

When node.type equals “folder” and it is opened, we render arrow right icon, otherwise, we render arrow down icon. We don’t render the arrow if it is not “folder”.

Next, we render the file/folder icons.

And then we call getNodeLabel and display node label.

Finally, if a folder is opened, we find its child nodes and render them. This process is repeated itself utils there is no children.

Every time we render child nodes, level will be increased by 1. We will use level props to calculate padding-left of the NodeItem.

Now we can import TreeNode component inside Tree.js. After that, we put Tree component in the render method of App.js. Our React app will be reloaded by itself and we will see something like this:

Make our component beautiful by styled-components

Let’s add the following code just right below the import statements:

const getPaddingLeft = (level, type) => {
  let paddingLeft = level * 20;
  if (type === 'file') paddingLeft += 20;
  return paddingLeft;
}

const StyledTreeNode = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 5px 8px;
  padding-left: ${props => getPaddingLeft(props.level, props.type)}px;

  &:hover {
    background: lightgray;
  }
`;

const NodeIcon = styled.div`
  font-size: 12px;
  margin-right: ${props => props.marginRight ? props.marginRight : 5}px;
`;

We’ve just created 2 styled components using styled-components. As you can see, the padding-left property is calculated by getPaddingLeft function. So higher level NodeItem will have bigger indentation.

Let’s put these components into render method of TreeNode:

const TreeNode = (props) => {
  const { node, getChildNodes, level, onToggle } = props;

  return (
    <React.Fragment>
      <StyledTreeNode level={level} type={node.type}>
        <NodeIcon onClick={() => onToggle(node)}>
          { node.type === 'folder' && (node.isOpen ? <FaChevronDown /> : <FaChevronRight />) }
        </NodeIcon>
        
        <NodeIcon marginRight={10}>
          { node.type === 'file' && <FaFile /> }
          { node.type === 'folder' && node.isOpen === true && <FaFolderOpen /> }
          { node.type === 'folder' && !node.isOpen && <FaFolder /> }
        </NodeIcon>
        

        <span role="button">
          { getNodeLabel(node) }
        </span>
      </StyledTreeNode>

      { node.isOpen && getChildNodes(node).map(childNode => (
        <TreeNode 
          {...props}
          node={childNode}          
          level={level + 1}
        />
      ))}
    </React.Fragment>
  );
}

Display child nodes

Right now there is no child node is rendered because isOpen property on each node is still undefined. Let’s go back to Tree.js and add this method:

onToggle = (node) => {
  const { nodes } = this.state;
  nodes[node.path].isOpen = !node.isOpen;
  this.setState({ nodes });
}

When onToggle is called, it switches the value of isOpen in the node object and also updates the state of Tree component.

We need to put this method into TreeNode.

render() {
   const rootNodes = this.getRootNodes();
   return (
     <div>
       { rootNodes.map(node => (
         <TreeNode 
           node={node}
           getChildNodes={this.getChildNodes}
           onToggle={this.onToggle}            
         />
       ))}
     </div>
   )
 }

Return to our website and we can see the result:

Thanks for reading, I hope this tutorial is helpful for you.

Integrating Facebook login into your React application

Besides of login using email and password, social media login is very popular these days. If you want to grow user base fast, it’s hard to imagine that you don’t want social media login. In this tutorial, I will help you to implement a Facebook login flow into your React application.

There are 2 methods to implement social media login

  • Use social media’s Javascript SDK. It works well for any Single Page Application like React, Angular, VueJS, etc. The SDK does the most hard work and you only have to call login method and handle the callback. This method only works for Facebook and Google since only them support Javascript SDK.
  • Use social media’s REST API. Almost every social media website (include Facebook, Google, Twitter, Github, LinkedIn etc..) support this method. But they are NO Single Page Application friendly since usually it requires our application to redirect to social media login page, thus breaks application state (unless you have saved) so they are more suitable when your website is rendered by server instead user’s browser. We could avoid this problem using a popup, but let’s discuss about this method in another post.

Before you start, you can grab the source code of this tutorial at here: https://github.com/davidtran/react-facebook-javascript-sdk-login

Let’s start

Step 1:

In order to integrate social media login of any platform, you have to create an app on that platform. For Facebook, you have to go to https://developers.facebook.com/apps/ and click Add a New App from My app dropdown. After your app is created, click on your app and go to Products > Facebook Login > Settings to set Redirect URL.

Step 2:

This is the code that you need to copy into index.html to enable Facebook login. You should insert it right after <body> tag. You need to replace your-app-id by your app ID.

<script>
    window.fbAsyncInit = function () {
      FB.init({
        appId: '1813842465324998',
        autoLogAppEvents: true,
        xfbml: true,
        version: 'v2.11'
      });

      // Broadcast an event when FB object is ready
      var fbInitEvent = new Event('FBObjectReady');
      document.dispatchEvent(fbInitEvent);
    };

    (function (d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) { return; }
      js = d.createElement(s); js.id = id;
      js.src = "https://connect.facebook.net/en_US/sdk.js";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
  </script>

Right after the line FB.init. We create a new event object “FBObjectReady” and broadcast that event object. This event let us know when FB object is ready which we will use in our FacebookLoginButton component.

Now let’s implement our Facebook login button.

Step 3 – Implement Facebook Login Button component

We create this component because we want to reuse it anywhere in our application. After created this component, we can place in the login form or in the top menu or anywhere that you want to have Facebook login feature.

Now create a new file FacebookLoginButton and paste the following code:

import React, { Component } from 'react';

export default class FacebookLogin extends Component {

  componentDidMount() {
    document.addEventListener('FBObjectReady', this.initializeFacebookLogin);
  }

  componentWillUnmount() {
    document.removeEventListener('FBObjectReady', this.initializeFacebookLogin);
  }

  /**
   * Init FB object and check Facebook Login status
   */
  initializeFacebookLogin = () => {
    this.FB = window.FB;
    this.checkLoginStatus();
  }

  /**
   * Check login status
   */
  checkLoginStatus = () => {
    this.FB.getLoginStatus(this.facebookLoginHandler);
  }

  /**
   * Check login status and call login api is user is not logged in
   */
  facebookLogin = () => {
    if (!this.FB) return;

    this.FB.getLoginStatus(response => {
      if (response.status === 'connected') {
        this.facebookLoginHandler(response);
      } else {
        this.FB.login(this.facebookLoginHandler, {scope: 'public_profile'});
      }
    }, );
  }

  /**
   * Handle login response
   */
  facebookLoginHandler = response => {
    if (response.status === 'connected') {
      this.FB.api('/me', userData => {
        let result = {
          ...response,
          user: userData
        };
        this.props.onLogin(true, result);
      });
    } else {
      this.props.onLogin(false);
    }
  }

  render() {
    let {children} = this.props;
    return (
      <div onClick={this.facebookLogin}>
        {children}
      </div>
    );
  }
}

Let’s me explain every methods in this component.

First of all, when componentDidMount is called, we add an event listener to listen to event FBObjectReady and initialize our component. We need to do it because if we call any methods in FB object and FB is undefined, our app will throw the error. When our component is unmounted at componentWillUnmount method, we call document.removeEventListener to clean up our listener and prevent memory leak.

Now at the method initializeFacebookLogin, we assign FB object as a property of our component and call a method to check login status. After that, the method facebookLoginHandler will check login status. If login success, it get user details and call onLogin callback which is props that is passed from parent component.

In the render method, we wrap the children by a div and set the handler for onClick event.

Step 4 – Integrate Facebook login button into our app

Here is the source code of App.js. I created this app using create-react-app.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import FacebookLoginButton from './FacebookLoginButton';

class App extends Component {

  state = {
    username: null
  };

  onFacebookLogin = (loginStatus, resultObject) => {
    if (loginStatus === true) {
      this.setState({
        username: resultObject.user.name
      });
    } else {
      alert('Facebook login error');
    }
  }

  render() {
    const { username } = this.state;

    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">React Social Media Login</h1>
        </header>

        <div className="App-intro">
          { !username &&
            <div>
              <p>Click on one of any button below to login</p>
              <FacebookLoginButton onLogin={this.onFacebookLogin}>
                <button>Facebook</button>
              </FacebookLoginButton>
            </div>
          }
          {username &&
            <p>Welcome back, {username}</p>
          }
        </div>
      </div>
    );
  }
}

export default App;

In App.js, we wrap Facebook button by component FacebookLoginButton. When user clicks on this button, it will authenticate user account in Facebook and call onFacebookLogin after finished. If login success, it stores username in the state and render welcome message.

Thanks for reading this tutorial.

If you have any concern, feel free to send me a message or leave a comment. 

Why Single Page App is not bad as you think

I just read the article Why I hate your Single Page App on Medium. As a long time React and AngularJS developer I understand some of his points. Building a SPA is not easy as it seems. It provides a some of advantages in User experience but it also requires a lot of effort to make it works properly.

Here are some reasons make people dislike SPA:

  • Too many SPA framework to choose and each framework has its own ecosystem that you have to evaluate carefully.
  • It takes more efforts to make UX smoothly.
  • It requires more developers to build. Your backend developer can build SPA but they won’t and never make it properly (this opinion comes from my experience when I have to work with backend developer).
  • You have to think carefully about the app structure.
  • Most of SPAs are not SEO friendly and unless you implement server-side rendering and it’s not a trivial thing.

But SPA also provides a lot of benefit for End-User:

  • Faster loading time. SPA only has to lot the initial scripts, after that it can send Ajax request to ask for more data and update the user interface. Tradition website has to reload the whole things after every clicks.
  • Your app responses better. When user do any action, the app is updated instantly. In some cases, you have to implement a spinner to help user understand that they app has responded to their action.
  • Your frontend is separated from backend thus easier to maintain the app.
  • Better development experience frontend developer.

The question comes down to when and where to use SPA.

If your website is really simple, for example: you just need to display news and information and you need SEO to increase visit so you don’t need SPA and a WordPress website is enough. When created my blog, I was thinking about using React or WordPress and I choose WordPress because my blog is pretty simple. I just need to install a theme and my blog ready to use.

About SPA, ask yourself this question: What was the last time that you used Gmail classic (the slow version of gmail)? Every clicks is expensive, right. It takes few seconds to reload the whole website. Switching between tabs and compose new email is much easier on the modern Gmail. Ask the same question for Facebook, Spotify, Netflix, Messenger…

So if your website have a lot of interactions, SPA is a great choice. For example, a POS app. Do you want to make it as a traditional website. Reloading the whole app after every click, really?

There are a lot of application for SPA: chat app, CRM, online file manager, travel planning… so you have to use the right tool for the job ;). It’s 2017 and the tools for building SPA have been improved. Personally, I enjoy developing apps with React and AngularJS. Here are few things that make me love React:

  • Everything you see on screen are components. Components are easy to develop and maintain.
  • You can prevent CSS conflict issue with some style libraries like StyledComponent or CSSModules.
  • Hot reloading helps you update your app without even reload your app.
  • GraphQL is a game-changer for data fetching, I believe it will replace REST.
  • Javascript has been growth a lot in recently years. ES6 and ES7 helps developer more productivity (Babel transforms your code to ES5 and your code can run on most of popular browsers)

Next time, if someone tells you that they have SPA, please show them some great examples of SPA like Gmail. Even better, ask them what kind of application they are going to build and tell them whether they should use SPA or not.

See more premium WordPress themes by TommusRhodus