Picture of a backpack, by Josiah Weiss

We’ve already spoken in this blog about WordPress’ new development stack and the revolution that comes with it, both for the platform itself and for the developers who are now forced to learn new stuff. Not long ago, for example, I published a post explaining how to use the @wordpress/scripts package to extend Gutenberg and add a button to its UI. As an author, I love writing tutorials because I can share something I know well and I feel like we can learn all together.

Unfortunately, I think tutorials hide a big problem: many of you follow them blindly without really understanding what’s happening, even if you get the correct result in the end. But most tutorials lack the “aha moment,” the moment of insight and comprehension where everything clicks in your head and you understand why things are the way they are.

So today I’d like to start a series of posts with an introduction to React to shed some little light. I want to demystify React and help you get better at it quickly. I want you to understand why React is the way it is and why things are the way they are. I want you to understand the principles behind React. I want you to write better code.

Functional Programming

Before talking about React, I think it’s worth spending a couple of minutes talking about functional programming, since many of the frameworks we used today rely on its principles. And React (along with Redux) is no exception.

Functional programming is a programming paradigm in which programs are built by applying and composing functions. You may think that, well, “programming” has always been about building and running functions, right? Not exactly. Bear with me.

Consider, for example, object-oriented programming. In OOP, programs are built by creating and composing objects, which can contain data, in the form of attributes or fields, and code, in the form of methods or procedures. See? Not functions, but objects.

So what makes functional programming special? Well, there are several aspects that characterize functional programming: pure functions, referential transparency, immutability, functions as first-order citizens, higher-order functions, etc, and I recommend that you study them on your own (or, if you want me to, we can talk about them in future posts). But, to keep this post short, today we’ll simply focus on one feature…

Pure Functions

One of the things that makes functional programming different from other programming paradigms is how it defines and works with functions. In FP, functions are pure, which means that they meet the following two conditions:

  1. It always produces the same result when given the same arguments
  2. It has no side effects

For example, this is not a pure function:

let previousName = 'David';
function greet( name ) {
  if ( previousName !== name ) {
    console.log( `Hello, ${ name }!` );
  } else {
    console.log( `Welcome back, ${ name }!` );
  previousName = name;
}Code language: JavaScript (javascript)

because it has several side effects. Namely, it modifies a global variable (side effect 1) and it outputs some text to the console (side effect 2).

Another impure function is the following:

function createElement( name ) {
  const id = Math.random();
  return { id, name };
}Code language: JavaScript (javascript)

because, as you can see, it doesn’t always produce the same result. Every time one calls createElement with a certain name, the result they get is different. After all, the id attribute is generated through Math.random

Pure functions are great for multiple reasons: they’re simple to understand and contain no surprises. You give them some inputs, they’ll return you a specific output. And this is great, because this way of defining the functions brings them closer to our mathematical understanding of what a function is: it maps every input to a well-defined output.

Components in React

What do pure functions and functional programming have to do? Well, let’s see if we can derive their relationship…

As you can read in its documentation, React is a JavaScript library for creating user interfaces through small pieces of code called “Components.” This is the first component you’ll see in their tutorial:

class ShoppingList extends React.Component {
  render() {
    return (
      <div className="shopping-list">
        <h1>Shopping List for { this.props.name }</h1>
}Code language: JavaScript (javascript)

Quite simple and even self-explanatory, isn’t it?

But wait for a second! This doesn’t look at all like a “pure function.” In fact, this is a class implemented using object-oriented programming.

Gif of woman making a quizzical grimace

Yup, you’re absolutely right. This is not looking good… did we just waste our time talking about functional programming?

Take a look at the previous component again. What does it look like? What does it do? Well, it’s a class with a single method (render) that generates some HTML to render a shopping list. This shopping list is always the same (duh, it’s a simple example), but it has one variable part: its title, where the class seems to use an internal property this.props.name.

So, if we don’t know anything about React yet and we only look at the code and try to infer what it does, we see the following:

  1. The component can receive a “name.” We don’t know exactly how it gets this name, but we know it does. After all, this.props.name is a pretty good clue.
  2. The render method produces some HTML to render a (static) list of “shopping elements”: Instagram, WhatsApp, and Oculus.
  3. The resulting HTML is not 100% static; it uses a “name” that can vary based on the value of a property.

See where I’m going?

Components Functions in React

We just described a pure function! We have a component that takes a value (name) and produces a well-defined output (the HTML). Does this mean we can move away from OOP and implement the previous component as a function?

Gif showing a man doubting about what's thinking

Sure! The overly-complicated class we’ve just seen can be re-written as a simpler and easier-to-understand pure function that receives props and returns HTML:

const ShoppingList = ( props ) => (
  <div className="shopping-list">
    <h1>Shopping List for { props.name }</h1>
);Code language: JavaScript (javascript)

This is the exact same thing we had, but way, way simpler. I’d even dare to say it’s the simplest thing I can implement as a programmer: a React component is nothing more than a function that takes some props in and produces an HTML out.

And this is precisely the first lesson you have to learn: your React component is a pure function: props in, HTML out. A component must not execute asynchronous functions to fetch data (as those are side-effects). A component cannot modify the properties it receives either (immutability).

So, one more time: a component simply takes some props in and produces the HTML output. Period.

But wait, if a component is that simple, how can we do anything useful with them? Well, stay tuned, because we’ll talk about this in the next post!

Featured image by Josiah Weiss on Unsplash.

Leave a Reply

Your email address will not be published. Required fields are marked *

I have read and agree to the Nelio Software Privacy Policy

Your personal data will be located on SiteGround and will be treated by Nelio Software with the sole purpose of publishing this comment here. The legitimation is carried out through your express consent. Contact us to access, rectify, limit, or delete your data.