A better introduction to React?
Unfortunately, most of the React tutorials out there have no consideration for best practices and don’t always teach you the “right” way to do React.
In this tutorial, I will go over the basics of React, and the most common bad practices that you might encounter.
This tutorial is going to be long, so make sure to get yourself some coffee!
Why choose React?
Before we get started, let’s stop for a moment and see why React indeed is the best choice. There are many other UI frameworks out there. Why should you choose React? Let’s compare the two most popular UI frameworks?—?React and Angular. Although Vue.js is gaining popularity, we won’t be taking a look at it in this comparison.
In React, you describe what to render (instead of telling the browser how to do it). This also means that the amount of boilerplate is greatly reduced.
Angular, on the other hand, even has a CLI which generates all of the component boilerplate for you. Does this seem a little bit off? There’s such a huge amount of boilerplate in Angular that they’ve even created a special tool to generate it for you…
In React you simply start coding, it has no component boilerplate that you have to generate. There’s some setup involved, but when it comes to the components, you can express them as pure functions.
ngFor directives in Angular feels awkward. On the other hand, JSX in React feels just like HTML, there’s no special syntax to learn:
On the other hand, if you want to start using Angular, you have to pick up a new language (Angular uses TypeScript), Angular CLI, directives, among other things.
Angular has two-way data binding, which means that changes to a form element will automatically update the state. This is a big downside and makes debugging much harder. You may never be 100% sure what caused your state to update.
React, on the other hand, has one-way data binding. Which is a big benefit?—?you will always know what caused your state to change, and debugging is so much easier.
In my opinion, React’s greatest strength comes from the fact that you aren’t even forced to use classes. In Angular all of the components have to be implemented as classes. Classes over-complicate codebase without providing any benefits.
In React, all of the UI can be expressed as a set of pure functions, and using pure functions to render the UI feels like a breath of fresh air.