An Introduction to React

Photo by Artem Sapegin on Unsplash

So, you wanna learn React? Its quite a daunting idea isn't it? No matter what background you come from, React has positioned itself at the forefront of a major paradigm shift within the context of Web 2.0. The days of jQuery are over, the days of brittle frameworks are numbered.

What does this mean? Well, to keep up with the times, we, as engineers need to make sure we’re on the cutting edge. React, along with Vue is on the frontlines of Javascript development, which means that if you want to make headway, you have to be on the front lines alongside them.

No fear! That's why I'm writing this article. I'm going to do my best to explain React and its concepts as simply as possible. Make no mistake, the best way to really bend your head around React is to get your hands dirty with it.

I’ve found for the most part that articles just lose you in the complexity of it all, so hopefully, this one will do the opposite.

We’ll tackle:

  1. Why use React in a project?

1. Why use React in a project?

Good question. Often, React is used in a project just so the engineers on the project can say that “We used React on the project” — let's not get into that pattern.

How would you answer me if I asked you, “Why would you use Ember or Backbone on a project?” I'm sure you would have specific reasons. Like most things programming related when it comes to using 3rd party libraries to do the heavy lifting for you, its a case of how much heavy lifting is needed. Heres some rules of thumb:

React is good for:

  • UI (User Interaction) intensive websites (bank interfaces, dashboards, personalization user flows, eCommerce etc) — think lots of moving parts, lots of data needing to be managed in an inter-related way

It's not to say that you couldn't use React for the below, but really, it would only be doing you so much justice:

  • Your blog

There are obviously exceptions to the above, but if you’re ever in doubt, just refer to the ReactJS website, where they clearly state (no pun intended):

“React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.”

At its core, React is really about managing change in a performant way. Your company About page has no need it for it, trust me.

What does React really do?

First off, it's important to note that React is not like Angular. So stop comparing the two. If you suffer from framework fatigue, your choice is really between Vue and React. I won't argue the benefits of the two as I feel like I’ve got passed framework fatigue and chosen React.

So how does React differ from the Javascript that a browser already understands? Well, whereas vanilla Javascript is concerned with actually manipulating the DOM that the browser generates, React is concerned with not having to render then entire DOM every single time data changes.

How do I explain that more clearly? Well, remember that the DOM (Document Object Model) is, in fact, one big object, right? Javascript is good with handling objects, but we’re talking about a really complex object here. Each time data changes, the entire DOM is recreated. This action is pretty expensive.

You may be thinking, well yeah — my countdown widget isn't going to have such a big effect on my website performance. Which is more than likely correct, but what if your countdown widget needed to talk to other siblings, parent and child components and pass data backwards and forwards, changing data when users performed certain actions?

That statement in itself was pretty confusing and intricate, now imagine the DOM re-rendering itself all those times in order to maintain the user experience appropriately? All you’re really doing at this point is using up your computer's resources. Enter React.

Before we continue, let's make sure we understand this:

Every time data on the page changes, the DOM is re-rendered, i.e created again to reflect the updated data. Even elements or components that have nothing to do with that data are re-rendered. That seems silly for 2018.

Great, now, React works very differently. Instead of re-rendering the entire DOM, React creates a Virtual DOM. What? Yup, the Virtual DOM. What this means, without going into too much detail, is that React only updates parts of the DOM where you, as the engineer, have told it to update its data.

So, instead of re-rendering the entire DOM each time there is some kind of user interaction, React is just re-rendering a component, or part thereof.

To summarise:

Every time data on the page changes, React re-renders the component whose data has changed by using a technology called the Virtual DOM. Nothing else on the page is effected, unless other components are talking to our component in question and they rely on the components state for their own state.

So now you know why React is so fast. Let’s move onto what you need to understand in order to use it.

2. React paradigms explained

Its probably time for a coffee break now because this section is going to get serious. We can break React paradigms into a few sections:

🔖 JSX

Many engineers think that JSX is a type of markup language: it is and it isn't. JSX simply makes React more elegant. It prevents us from having to write out bloated function calls when we want to use a component within our application. As web engineers, being familiar with HTML syntax, brings JSX closer to home. Furthermore, the ability to use props like HTML attributes helps ease the learning curve.

An example of JSX in React

⚡️ Lifecycle

It's really important to understand the lifecycle of React components. Stateful components have methods we can use to update state. They are called at different points in the lifecycle. We can generally break those down into three groupings: Mounting, Updating and Unmounting. Remember the Virtual DOM we were speaking about? Well, these lifecycle methods relate directly to when your components are rendered into the Virtual DOM.

I don't have enough time to go through all the Lifecycle methods, so I’m just going to list the most prevalent, and you can do further reading based on your components’ requirements

Mounting

constructor: Called before the component is mounted.

  • Set initial state

componentDidMount: Invoked immediately after a component is mounted in the Virtual DOM.

  • You can make API calls here using a library like fetch or axios

Updating

render: The only required method in a Stateful React Component (class)

  • Do not modify state in this method — in other words, we want to keep state and props pure (no updating/changing) at this point.

componentDidUpdate: Invoked immediately after updating occurs.

  • You need to check if props before the update are equal to the props after the update here.

Unmounting

componentWillUnmount: Invoked before a component is unmounted

  • Remove event handlers
A contrived example of React Lifecycle

🍰 Components

Components are the building blocks of React. One of the major mind-shifts when starting to use React is thinking about how your application implements components. A contrived example is a form:

An example of using components in React

Notice how we use JSX here render components? Also, notice how even though this may not look like valid HTML structure, it really isn't HTML until it's rendered into the DOM. The <Input /> component, for instance, could contain a <label> and other markup. This keeps our parent component clean and easy to understand. We can pass props around here with ease.

You get different types of components.

Stateful Components: use the class syntax, and allow you to use React lifecycle methods and state.

Stateless Functional Components: Are static components or otherwise known as dumb components that can use props. They are more for show than anything else and cannot use Lifecycle methods. You’ll notice they are also stored in a const rather than a class

PureComponents: Pure Components are more performant than using Stateful Components, the only difference being that you cannot use shouldComponentUpdate() as Pure components do not alter state or props.

🔩 Props

Components can accept props or properties if you were confused what props was short for. You can pass data-types (int, string, object, function, boolean) to props as values. Props can be any kind of data you wish to include on a component, for instance:

An example of props in React

📢 State

State eludes many newbies to React. Engineers often get confused between what is considered state and what is considered props. There are some pretty large differences. Essentially state is just an object. This object determines how the component renders and behaves. state can be updated by certain events as well, a click or submit for instance.

state is not a new concept in web development. You witness contrived examples all over the web: modals, dropdowns, tabs and accordions all have state. A modal can either be open or closed, therefore it has a state.

In React we use state specifically for these situations. Instead of statically adding a class to a modal for it to open, we use state to determine whether that class should be applied or not.

React provides us with a special method called setState which allows us to update state in a dynamic and non-destructive way. See the Gist below:

An example of setState in React

As you can see, we’re using setState to set the state of isOpen to the opposite of whatever it currently is, that method is bound to a click event on a button.

Due to the nature of how React works, we useisOpen in a ternary operator to decide on whether the modal should have the active class appended (considering that the active class has the correct CSS to open our modal) — while this is a simple example, it demonstrates how you would go about using state in a React application and how it makes building user interactions incredibly powerful.

One thing to know about state is that you can’t update it directly. So doing something like this: this.state.isOpen = false is not allowed. Always use setState when it comes to updating state.

🚕 Events

Events also work a little differently in React. React provides what is known as Synthetic Events — you are probably already pretty familiar with all of them listed on the React website. Attaching an event to a button or form is not quite how best practices go in vanilla Javascript. Have a look at the Gist below:

An example of handling events in React

We’re using a Stateful component here as we need to include some event methods to tell React what to do when the form is submitted. Note that simply adding a class method isn't enough. We need to make sure we’re binding this otherwise React won't know that we’re referring to the instance of this component class.

If you don't wish to use this approach, you could also do something like this: <form onSubmit={() => this.handleSubmit()}> — by doing so, this is intrinsically bound, so no need to do so in the constructor method.

Conclusion

I hope that this article has given you a broad understanding of some of the inner workings of React. React is a lot to take in and I barely scratched the surface. Look out for some of my upcoming articles where we will take a look at some of Reacts API’s.

| I tinker with Front-end at 10up.com | Conference Speaker | Writer | Traveller | Runner | Indie Games | Xbox | Coffee | Bourbon

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store