Uncategorized

The perfect career path

Look at me! Look at all the things I’ve done!

Introduction

Irony on

Hello, this is a blog post that will explain the many different ways that my career is actually better than yours. I will try to use the most condescendent tone possible, to make sure you understand I am just a better human being than you, in any way, shape or form possible. Therefore, I can’t accept any opinions that is slightly different than mine, and I will get really angry if you express one of those opinions.

Irony off

The perfect career

As developers, we are blessed with amazing opportunities to change people’s lives, to grow and to learn amazing things. We are also in a society that makes information and knowledge very easy to access. We are always in contact with blog posts, social media gurus, podcasts… Every single one of those medium delivers a message, selling a way of life, a way to get better, how-to advices…

It’s easy, with all those informations to believe that to have the right to be called a developer, or a software engineer or whatever title, you need to make sure you check all the boxes:

  • Have a blog.
  • Contribute to open source.
  • Have 346 different side-projects, at the same time.
  • Spend 3 hours and 27 minutes a day listening to podcasts.
  • Spend 4 hours of your free time learning new technologies and staying up to speed with your industry.
  • Speak to at least 8 conferences a year, which needs to be in at least 4 different continents, or 3 different planets, pick the one that’s the most confortable to you.
  • Spend 48 minutes on social media every day interacting with your audience.
  • Have at least 14 of your side-projects generating an income.
  • Read 3 books every 12 hours. One of those books must be from an old white man that coded on some cardboard stuff 500 years ago. Another one must be about money and explain to you how to get rich quick.
  • You created 27 startups in 3 years. 52 of them failed.
  • Exercise 92 minutes a day. Preferably when you wake up at 5AM.
  • Not working for someone else, only losers do that.

Some old white man. You should have read all his books by now…

Congratulations, you made it as a developer!

The uniqueness of your path

It’s easy to become overwhelmed by all of the informations and advice you read or hear. It’s easy to feel inadequate, and to push yourself hard to try to become that person. But don’t worry.

All of this is bullshit.

The perfect career exists, but it’s the one you decide for yourself. It’s going to be different for every single person. You don’t want to blog? Don’t do it. Don’t feel like contributing to open source? Forget it then.

You want to do your job for 7-8 hours a day, do it well, and not touch anything computer-related for the rest of the day? Sounds like a good plan.

The perfect career is the one that is in line with your values. Do not compare you career to anyone else’s. We are all different, and our goals will always differ. And you can’t compare the chapter 2 of your story to a chapter 23 of another developer’s story.

Chasing mastery? Don’t trouble yourself, you won’t achieve it. Mastery is a nice ideal we all dream of. It’s a beautiful thing in the horizon that gives us a compass. You’ll get close, but that’s it, and that’s okay.

I, personally, have a blog. It happens that I don’t write for a few weeks. Because I don’t want to, or life gets in the way. I used to feel bad, I don’t anymore. I don’t speak at conferences, I don’t intend to. I don’t contribute to open source. I don’t have that desire. I don’t have any side projects going on right now. I work for someone else, and I’m very happy with that someone else.

My path is unique, so is yours. It doesn’t make it any less awesome.

Relax, enjoy the ride

The beauty is in the journey. Be proud of what you do. Align your career with your values. Deploy on Friday, or don’t. Whatever. Just don’t be a dick about it. Learn only Javascript, or PHP. Or anything else. Whatever. Just don’t be an ass about it.

Life too short to worry about things like these. ❤

Uncategorized

How to use the state hook in React

A look at how to use the Hook state

Introduction

Hooks have been introduced in React 16.8. This feature completely changed the way we write our components. As you may know, before Hooks, you couldn’t use state in functional components. Whenever you needed to add state to a functional component, you needed to re-write that component as a class… Annoying. The state Hook finally solves that issue.

How to use it

The state hook is used as follow:

import React, {useState} from 'react';

const CreateDebate = () => {
    // We declare a state variable, called debateName
    const [debateName, setDebateName] = useState("");

    return (
        <div>
            <p>Enter a debate name:</p>
            <input type="text"
            value={debateName}
            onChange={e => setDebateName(e.target.value)}>
        </div>
    )
}

We have here a very simple piece of code. We create a functional component called CreateDebate. That component renders a div element. Inside that element, we find a paragraph with an input. We use the Hook state, with useState, to add state to this component. We’ll go in detail on how it works, but for now, let’s compare that with the same functionality with a class component.

import React from "react";

export default class CreateDebateClass extends React.Component {
  constructor() {
    this.state = {
      debateName: ""
    };
  }

  render() {
    return (
      <div>
        <p>Enter a debate name:</p>
        <input
          type="text"
          value={this.state.debateName}
          onChange={e => this.setState({ debateName: e.target.value })}
        />
      </div>
    );
  }
}
Function components

React Hooks do not work with classes. They only work with functions. As a reminder, function components can be written in different ways:

function MyFunctionComponent() {
  //Hooks go here
  return <div />;
}
const MyFunctionComponent = () => {
  //Hooks go here
  return <div />;
};

The React team recommends the term Function components to talk about these functions. Before Hooks, you may know them as Stateless components or Functional components.

A hook in detail

What is a Hook exactly? A Hook is a special function. It allows you to use certain React features. Our first example details the state Hook. When using that hook, we can use the state feature you are used to see in class components.

To use that particular hook, you first need to import it.

import React, { useState } from "react";

const StatefulFunction = () => {
  // Your code...
};

Before, when you had to use state inside a component, that component had to be a class. Now, we can simply import the useState function for that!

For those who don’t know, or remember, state is a React feature. It allows you to keep variables values between function calls. Usually, when a function is done with its job, the variables disappear. Which would cause some problem every time we need to update our interface and re-render our components. With a state, we can keep and update variables over time without losing our progress.

const Example = () => {
  const [firstName, setFirstName] = useState("Damien");
  return <div />;
};

The useState function declares a new state variable. The function is a new way to use this.state you found in classes. As you can see above, useState takes one argument. This argument represent the initial state. In a class, that would be done in the constructor. In a class however, that initial state needs to be an object, even if you only have one string or integer in your state.

class Example extends React.Component {
  constructor() {
    this.state = {
      firstName: "Damien"
    };
  }

  render() {
    //...
  }
}

With useState, that can be anything you want. Here, I want my initial state to be a string.

WHAT DOES IT RETURN? WHAT’S UP WITH THAT SYNTAX?
const [firstName, setFirstName] = useState("Damien");

The useState function returns two values. The first value is the current state, the second is the function that updates that state. In our case, firstName is the current state, and setFirstName is a function that will allow me to modify the state value.

The syntax might seem a bit odd if you are not used to it. This is what we call array destructuring, a cool little syntax feature we got from Javascript ES6. This syntax allows us to assign the first item in the array to a variable, here called firstName, and the second item of the array is assigned to a variable we called setFirstName. Note that those names are completely arbitrary and not part of the React library. Choose whatever variables feel right for your code.

The array destructuring syntax used for useState is the same as the following code:

let firstNameVariables = useState("Damien"); // This is an array with two values
let firstName = firstNameVariables[0]; // First item
let setFirstName = firstNameVariables[1]; // Second item

This way of accessing the values is a bit verbose and confusing. Therefore, the array destructuring feature is a nice way to write the useState hook.

Read state

In a class component, you would read from this.state.debateName:

<p>The debate name is {this.state.debateName}.</p>

With the state hook, we can now simply use debateName:

<p>The debate name is {debateName}.</p>

Remember: This variable name is the one you give as the first item the useState function returns.

Update state

To update state in a class component, you would use setState:

<input
  value={debateName}
  onChange={e => this.setState({ debateName: e.target.value })}
/>

With a state hook, you will use the function provided by useState, the second item it returns:

<input value={debateName} onChange={e => setDebateName(e.target.value)} />

In my example, I’ve called this function setDebateName. Remember that this name is not part of the React API. I’ve chosen the name of this function, so make them as clear as possible. Notice that we also don’t need this, because we already declared debateName and setDebateName.

Recap

Let’s recap how we can use a state hook:

import React, { useState } from "react";

const DebateNameInput = () => {
  const [debateName, setDebateName] = useState("");

  return (
    <div>
      <input value={debateName} onChange={e => setDebateName(e.target.value)} />
      <p>The debate name is {debateName}.</p>
    </div>
  );
};
  • On the first line, we make sure to import the useState function from React.
  • We create a function, using the arrow syntax, and give it the name DebateNameInput.
  • We call the useState function. It returns an array with two values, the current state and the function that acts as a setter. Thanks to the array destructuring syntax, we can assign those values in one line. We call the first one debateName and the second setDebateName. The useState function takes one parameter, which represents the initial state. In our example, an empty string.
  • Our function returns some JSX. The input takes the current state as its value. We gave it the name debateName. Whenever that input registers a change event, we call setDebateName with the input’s new value as a parameter. This function will then replace the current debateName value with the new one.
  • React re-renders the component with that new state value.

Using several state variables

So far, we’ve only worked with one state variable at a time. Of course, you will most likely have more than one state variable in your component. You can use several useState functions if you want:

function fruitBasket = () => {
  const [numberOfBananas, setNumberOfBananas] = useState(0)
  const [numberOfApples, setNumberOfApples] = useState(3)
  const [numberOfPeaches, setNumberOfPeaches] = useState(2)

  //... rest of your code
}

Here, we use three different useState functions to declare three state variables, and their 3 different setters.

You don’t have to use several state variables. useState can also hold objects and arrays, so this is entirely possible:

function fruitBasket = () => {
  const [numberOfFruits, setNumberOfFruits] = useState({bananas: 0, apples: 3, peaches: 2})

  //... rest of your code
}

One thing to know: updating the state variable numberOfFruits is different from the this.setState in classes. In the state hook, the setter function replaces while the setState function merges. Which means, to properly updates numberOfFruits, you’ll need to:

setNumberOfFruits({ ...numberOfFruits, bananas: 2 });
setNumberOfFruits({ ...numberOfFruits, apples: 3 });

By using the spread operator (...), we keep the current state and only replaces the variables that needs to change. The first function call will replace the amount of bananas to 2, the second will replace the amount of apples to 3.

Uncategorized

The Dreyfus model of skill acquisition

A model to access competencies and skills

What model now?

The Dreyfus model of skill acquisition is used to access to level of development of competencies and skills of people who are learning something new.

The model was proposed by the Dreyfus’s brothers Stuart and Hubert in 1980. They studied how people attain mastery and came up with five stages on the journey from novice to expert.

The model is applicable per skill. You are not a novice nor expert at every single skill. Chances are, you are mostly average at most things. You can be a novice basketball player, and be an expert cook. Or vice versa.

I’m quite notice at cooking. I can follow a set of clear rules, have a clear recipe. But, I don’t really know what is going on.

Let’s jump into the different stages.

2) Novices

When you begin to learn something new, you are a novice. You have no skill or experience. Novices are not particularly interested in learning, but they need to succeed. They need an immediate goal.

When I started to learn how to code, I wasn’t interested about how the DNS worked, how HTTP requests were happening, and how a website was working. I just wanted to see a page, my HTML page appear on the browser.

Thus, novices need recipes, context-free instructions. Recipes are often used in the context of cooking, but they are useful in every domain for beginners. Do A, then do B. If X, do Y…

I’ll use the example of taxes to illustrate this. I, and many others, have no idea what we are doing. You follow the government instructions. On this case, fill out your revenues for the year, on that one, fill out the number of people in your house… I don’t want to learn that stuff, I just want to achieve something. Get it out of the way, and move on.

The problem with novices, and recipes is that they won’t know how to react if an error occur. If the government sends me a notice telling me the numbers are wrong, I won’t know what to do, unless there is another context-free recipe to help me rectify my mistake.

We also have to be careful not to overwhelm novices with too many rules. If X happens, then do Y. But if W occurs, check M, if M is A, then do W….

Too ambiguous, too hard to understand. Keep it simple. There is a balance to find.

2) Advanced beginners

The second stage on the path to mastery is the advanced beginner. Advanced beginners can start to free themselves from the recipes and rules a little bit. They can try some tasks on their own, based on their past experience, but they will have problems troubleshooting. If problems arise, they most likely won’t be able to solve them on their own.

Advanced beginners don’t want the big picture. They want the information fast and get things done. On his way to master a new programming language, an advanced beginner doesn’t care which data structure would be the most appropriate for a particular task. Nor would she care which way to loop through an array is the most performant.

The larger context is irrelevant to them. They can start formulating some overall principles, but the big picture will probably be dismissed as not useful yet.

3) Competent

At the third stage, learners can start to fix problems on their own. They can also troubleshoot and think about new problems. They seek out and apply advice from experts. They might be described as resourceful or to have initiative.

At this stage of their journey, they can also start to mentor novices and won’t annoy the experts overly much with questions. They are able to use their experience to be more autonomous.

4) Proficient

At the fourth stage, practitioners need the big picture. They can understand the larger context and need it to guide their work. They are frustrated by oversimplified information. They would be really happy if they called tech support and got a: “Is your computer turned on?”.

Importantly, they are able to reflect on their performance and adjust it for next time. This sort of reflection was not available before this stage.

They are able to understand and apply maxims. Maxims are proverbial, fundamental truths that can be applied to a certain context. This is what differentiates them from recipes. For example, a novice might be hearing about Test Driven Development and that good code must be tested. The novice might want to write tests for everything, without knowing which feature to test, and how to test it. At stage 4, they would know how to apply the TDD behavior correctly.

5) Expert

At long last, you are an expert. Experts are the primary source of knowledge. Experts work from intuition. Often, they are not able to properly articulate why something works. It just feels right to them. Ever notice some professional chefs telling you to add some salt and pepper? They never mention how much. It’s a touch, or a pinch, or just pouring some stuff and then stop. They know, from experience, that this is the right amount of seasoning to make a dish perfect. But they are no rules here, it completely up to the expert to know what is right in that context.

Experts also know the difference between important details and irrelevant details. They know what can be brushed aside and forgotten and what we need to focus on.

Finally, experts are painfully aware of what they don’t know yet. On the contrary, novices can suffer from what is called the second order incompetence: being unskilled and being unaware of it.

Conclusion

Some closing thoughts:

It’s highly unproductive to treat everybody the same. Experts and novices have a huge difference a productivity between them. Novices need to be guided. Experts don’t perform well with rules. A study of airline pilots showed this. The experts wrote rules for the novices pilots to follow. The novices skills improved as a result. But when they asked the experts pilots to follow their own rules, the experts’ performance actually decreased…

So, where are you on your journey to mastery?

Thank you for reading ❤

Uncategorized

Create a calendar plugin with vanilla Javascript

Moving away from all the frameworks and libraries

Introduction

When we hear about Javascript, we often hear about libraries and frameworks. There are about five gazillion choices today on how to use Javascript. Yet, we often forget that we can still use good old classic Javascript, without frameworks or libraries. In this article, we’ll build a plugin using nothing but vanilla Javascript. This plugin, quite simple, will allow us to include a calendar in an HTML page.

Setting up

We need three files, one HTML file, one CSS file and one Javascript file. Let’s start with our Javascript file, because this will be where we have the most work to do.

Plugin Skeleton

(function (root, factory) {
  root.myCalendar = factory(root);
})(this, (root) => {
  let privateVar = "No, No, No...";
  let init = () => {
    console.log("Init the calendar");
  };
  return {
    init,
  };
});

The first thing we need to do is to make our plugin available for our environment. We do this by using an IIFE (Immediately Invoked Function Expression). As you can see, we wrap our first function into parentheses, turning it into an expression that we call right away.

IIFE are useful to encapsulate code. My plugin’s code won’t be accessible from outside the plugin. But we’ll see that later.

Let’s break the code above a little bit:

In the main body of our function we do:

root.myCalendar = factory(root);

What is root? This is the first parameter of our IIFE, this. So, in a browser, this is the window object. We set window.myCalendar to factory(root)factory, the second parameter of our IIFE, is a function. This is, in fact, our plugin content.

The beauty of this approach is that window.myCalendar will only contain whatever my function returns. So, I’ll be able to call window.myCalendar.init(), but window.myCalendar.privateVar will be undefined, because it’s not returned by our IIFE.

Importing in our index.html

We already have a plugin! It doesn’t do much, but it works. Let’s create a HTML file and test it out.

<html>
  <head>
    <script src="simple-calendar.js"></script>
    <script>
      window.onload = function () {
        myCalendar.init();
        console.log(myCalendar.privateVar);
      };
    </script>
  </head>
  <body></body>
</html>

We load our Javascript file. I called it simple-calendar.js but name it whatever you wish. Then, after the window is done loading, inside the onload event listener, I’m called myCalendar.init() and console.log the myCalendar.privateVar variable.

Note: window.myCalendar and myCalendar is the same here 😉

So, here’s what I see in my console:

Console private variables

Great! The init function prints what we expected and privateVar is indeed undefined because it is not returned from our IIFE, so our plugin doesn’t know what you are talking about!

The CSS

Let’s get that out of the way, because this is not the point of the article. Create a CSS file and put the following styles inside it:

#calendar {
  background: #fff;
  border-radius: 4px;
  color: #222629;
  overflow: hidden;
  margin-top: 20px;
  max-width: 400px;
}

#calendar.hidden {
  display: none;
}

button {
  border: none;
}

#calendar .header {
  background: #ddd;
  height: 40px;
  line-height: 40px;
  text-align: center;
}

#calendar .header + div {
  border: 1px solid black;
}

#calendar .month {
  display: inline-block;
  font-weight: bold;
}

#calendar button {
  background: none;
  color: inherit;
  cursor: pointer;
  font-size: 23px;
  font-weight: bold;
  height: 100%;
  padding: 0 15px;
}

#calendar button:first-child {
  float: left;
}

#calendar button:last-child {
  float: right;
}

#calendar .cell {
  background: #fff;
  color: #5d5d5d;
  box-sizing: border-box;
  display: inline-block;
  padding: 10px 0;
  text-align: center;
  width: calc(100% / 7);
  cursor: pointer;
}

#calendar .cell:hover {
  color: white;
  background-color: blue;
}

#calendar .day {
  font-size: 0.8rem;
  padding: 8px 0;
}

#calendar .cell.today {
  background-color: blue;
  color: white;
}

#calendar .day {
  color: black;
}

Don’t forget to import it in our HTML file. In the <head> of our page, add the following line:

<link rel="stylesheet" href="calendar.css" />

Of course, replace the calendar.css with the name of your file.

Adding functionality

Ok, it’s very cute, but my plugin still doesn’t do anything here… Let’s begin.

Months, Days and Today

I’ll first need to get the months list, days list and today’s date. I want my calendar to focus on today’s date by default. So, in our plugin, above the private variable, let’s add those:

// Beginning of the file cut for brevity
    let monthList = new Array(
      "january",
      "february",
      "march",
      "april",
      "may",
      "june",
      "july",
      "august",
      "september",
      "october",
      "november",
      "december"
    );
    let dayList = new Array(
      "sunday",
      "monday",
      "tuesday",
      "wednesday",
      "thursday",
      "friday",
      "saturday"
    );
    let today = new Date();
    today.setHours(0, 0, 0, 0);
    let privateVar = "No, No, No...";

  let init = () => {
    console.log("Init the calendar");
  };
  return {
    init,
  };
});

Good, everything is setup. Now, we can start to modify the DOM to implement our calendar. Obviously, this step needs to be done inside the init function. We want the calendar to appear when we initialize our plugin.

There are a few things we need to do:

  • Create a header with the name of the current month and the current year. This header will also have next and previous buttons to navigate between months.
  • Below the header, we will have the list of days, from Sunday to Monday.
  • Finally, we will have the days in the current month.

The header

// Our variables are up there
let init = () => {
  let element = document.getElementById("calendar");

  let currentMonth = new Date(today.getFullYear(), today.getMonth(), 1);

  // Creating the div for our calendar's header
  let header = document.createElement("div");
  header.classList.add("header");
  element.appendChild(header);

  // Our "previous" button
  let previousButton = document.createElement("button");
  previousButton.setAttribute("data-action", "-1");
  previousButton.textContent = "\u003c";
  header.appendChild(previousButton);

  // Creating the div that will contain the actual month/year
  let monthDiv = document.createElement("div");
  monthDiv.classList.add("month");
  header.appendChild(monthDiv);

  // Our "next" button
  let nextButton = document.createElement("button");
  nextButton.setAttribute("data-action", "1");
  nextButton.textContent = "\u003e";
  header.appendChild(nextButton);
};

We have here just a few elements added with Javascript. We don’t use anything fancy, just the classic Javascript API with createElementappendChild and setAttribute. We created our div element for our header, that will contain the current’s month name. We also created our previous and next buttons.

Notice this line:

let element = document.getElementById("calendar");

This element is what will contain our calendar. We put it inside an element with the id calendar. This is a choice I made, but we’ll make it customizable later. But that means we need to add an element with the proper id in our HTML:

<!-- The <head> tag is up there-->
<body>
  <div id="calendar"></div>
</body>

That’s it for the HTML. And sure enough, we can see the header in our page.

Uncategorized

What are Javascript’s IIFE?

Exploring another famous Javascript acronym

Another acronym?

We loooove acronym don’t we? KISS, DRY, TDD, LOL… So many concepts behind them, so much to remember. So, what’s an IIFE in Javascript?

IIFE stands for Immediately Invoked Function Expression. You create a anonymous function and immediately call it, you know, with the parenthesis.

Below is a beautiful function expression, dated to about 4000BC. Author: Anonymous

Here, we store a anonymous function in a variable. Later, we call that function by adding those parenthesis.

const myFunction = function () {
  console.log("A function has no name.");
};

//Calling the function
myFunction();
// A function has no name

An IIFE combines the anonymous function and the call step.

(function () {
  console.log("This is IIFE.");
})();

What is happening here? 3 things:

  • We have an anonymous function. That includes the function keyword, the parenthesis, the curly braces and the console.log statement. This is a function declaration
  • That function declaration is surrounded by parenthesis. This is what turns a function declaration into a function expression. Who knew two little parenthesis could have so much power?
  • Finally, the final parenthesis are calling that function expression, running the body of that function.

Congratulations, you just understood what an IIFE is made of! Which now begs the question, why the hell would I want to use one of those things anyway?

The why behind IIFE

The main reason why you would want to use an IIFE is to not pollute the global scope, and keep the content of your choosing inside your function private.

Because of the surrounding parenthesis, the IIFE has its own scope, which can not be accessed from the outside. Whatever you return from an IIFE will be the only things you can access from outside that IIFE.

(function () {
  let sayMyName = "Damien";
})();

console.log(iife.sayMyName); // sayMyName is not defined

If I want to make those variables accessible, I need to return it from that IIFE:

const iife = (function () {
  let sayMyName = "Damien";
  let privateVariable = "No trespassing!";

  let greeting = function () {
    console.log("Hello from the IIFE");
  };

  return {
    sayMyName,
    greeting,
  };
})();

console.log(iife.sayMyName); // Damien
iife.greeting(); // Hello from the IIFE
console.log(iife.privateVariable); // privateVariable is not defined

The plugins way

IIFE are quite popular when writing Javascript plugins. That allow the users to use the functionality several plugins without having their global scope invaded by thousands of variables. IIFEs just populate the global scope with what they need to work, usually just one variable.

You can find an example in this Calendar plugin article, where I wrote a simple Calendar plugin.

Basically, a plugin could look something like this. It’s a bit more complicated, but it’s still an IIFE.

(function (globalScope, whatWePopulateTheGlobalScopeWith) {
  globalScope.myCoolPlugin = whatWePopulateTheGlobalScopeWith();
})(this, function () {
  let launchThePlugin = () => {
    document.title = "PLUGIN LAUNCHED";
  };
  return {
    launchThePlugin,
  };
});

A bit more technical, let’s break it down.

Notice that we still have the IIFE skeleton. A function declaration, surrounded by parenthesis, and immediately called. What might be throwing you off is that when we call the function expression, we give it parameters. The first parameter is this, which is the global scope.

In my case, the global scope in the window object, because my plugin runs in a browser. But it could be anything. The second parameter is a function.

In the main body of the IIFE, we populate the globalScope with whatever that function provided in the second parameter will return. Here, I’m returning a function called launchThePlugin. Which means, once this IIFE is executed, window.myCoolPlugin will equal the object that function returned.

The main body of the IIFE will populate the global scope, the other function will manage the plugin’s functionalities. So, when I import my Javascript file in my HTML, I can run myCoolPlugin.launchThePlugin() (or window.myCoolPlugin.launchThePlugin()). This function will update the document’s title.

I can add a whole bunch of things in that function, but as long as I do not return it, it will not be accessible from outside this function.

And that is the power, usefulness, awesomeness of IIFEs.

Hope it was clear! If not, let me know! ❤

Uncategorized

Implement Code Splitting in React

One way to improve performance in React

Understanding React bundling

By using tools such as Webpack or Browserify, React applications are bundled. Bundled means that the files inside your application are imported and merged into one file. This way, when you import your application in a webpage, you only need to import one file.

Assuming you have two files:

// greeting.js
export const greeting = () => {
  console.log("Hello my friend");
};
// index.js
import { greeting } from "./greeting.js";

greeting();

A bundle would transform these files into:

const greeting = () => {
  console.log("Hello my friend");
};

greeting();

Of course, this is oversimplified, because there are a lot of steps in the bundling process, but you get the idea.

Bundling issue

Bundling is great when your application is small, but as your application grows, the bundle grows as well. That means, if a user loads the home page of your web app, she will still have to import the bundle of your ENTIRE application…

This can cause performance issues. To avoid this, we can implement code splitting. In this article, we will use code splitting based on our routes.

import()

Code splitting implies that we will have our code into smaller pieces. Yet, we won’t need to change the way our code is written. We will change the way we import our components. We need to tell the tool in charge of bundling our code when to split our code.

If you use create-react-app, which uses Webpack, you will start by using the dynamic import function. The syntax goes as follow:

import("./myModule.js").then((myModule) => {
  myModule.init();
});

The syntax uses a promise to wait for the Javascript file to be loaded before using the content of the file.

React.lazy

React implements this sort of logic with React.lazy. It allows you to display a component just like any other component, the difference being that it will be imported dynamically.

import React, { lazy } from "react";

const DynamicallyImported = lazy(() => import("./DynamicallyImported.js"));

React.lazy takes a function that returns a dynamic import. This component will not be imported with the rest of the application, like you would without any code-splitting implemented. React will import this component only when it is rendered for the first time.

Note that the component that you dynamically import needs to be a default export, and of course, it needs to export a React component.

So, if we implement code-splitting based on our routes, this means that if a user checks our application and never travels to a particular route, that route won’t be imported at all. A huge benefit for your user, as you will only force her browser to import exactly what she needs, and nothing more.

Suspense

A component imported with React.lazy must be used inside a Suspense component. A Suspense component provides a fallback content. This content acts an indication that our lazy component is loading.

import React, { lazy, Suspense } from "react";

const DynamicallyImported = lazy(() => import("./DynamicallyImported.js"));

const CoolComponent = () => {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <DynamicallyImported />
      </Suspense>
    </div>
  );
};

Such dynamically imported components don’t need to be directly surrounded by a Suspense component. One Suspense component can also handle several dynamically imported components:

import React, { lazy, Suspense } from "react";

const DynamicallyImported = lazy(() => import("./DynamicallyImported.js"));
const AnotherDynamicallyImported = lazy(() =>
  import("./AnotherDynamicallyImported.js")
);

const CoolComponent = () => {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <header>
          <h1>Hello there</h1>
        </header>
        <div>Something else</div>
        <DynamicallyImported />
        <p>Divider</p>
        <AnotherDynamicallyImported />
      </Suspense>
    </div>
  );
};

Code splitting based on our routes

Routes are a good place to start implementing code splitting. Going from one page to another, users are expecting the page to load as a block and to wait a bit for the page to be rendered. It makes it a good place to start while being sure to not alter the user experience.

In this example, I’ll use the popular react-router-dom package for the routing of my React application. Of course, it can be used with any library you prefer.

Before code splitting, your Router component could look something like this:

import React from "react";
import { Route, Router, Switch } from "react-router-dom";
import Header from "./Header";
import About from "./pages/About";
import Blog from "./pages/Blog";
import Contact from "./pages/Contact";
import Home from "./pages/Home";
import Products from "./pages/Products";
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default () => {
  return (
    <Router history={history}>
      <Header />
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/products" component={Products} />
        <Route path="/blog" component={Blog} />
        <Route path="/contact" component={Contact} />
      </Switch>
    </Router>
  );
};

If you’ve used react-router-dom before, this will be familiar. If not, this is how routing is implemented using this library.

With this code, whenever a user travels to one page, the entire application code will be loaded. Because we have only one bundle, there can’t be any other way! This can be expensive.

We’ll need to do three things to make code splitting work and having several bundles:

  1. Import React.lazy and Suspense.
  2. Modify how we import our components (Home, About, Products, Blog and Contact) to make it dynamic using React.lazy and import()
  3. Use the Suspense component to provide a fallback in our return function.
  4. You would change the first line to:

import React, {lazy, Suspense} from "react";

Done!

  1. Import dynamically our components. Change line 4 to 8 like so:
const About = lazy(() => import("./pages/About"));
const Blog = lazy(() => import("./pages/Blog"));
const Contact = lazy(() => import("./pages/Contact"));
const Home = lazy(() => import("./pages/Home"));
const Products = lazy(() => import("./pages/Products"));

Awesome!

  1. Finally, surround the components dynamically imported with the Suspense component:
export default () => {
  return (
    <Router history={history}>
      <Header />
      <Suspense fallback={<div>Loading page...</div>}>
        <Switch>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
          <Route path="/products" component={Products} />
          <Route path="/blog" component={Blog} />
          <Route path="/contact" component={Contact} />
        </Switch>
      </Suspense>
    </Router>
  );
};

Fantastic! You have successfully implemented code splitting in your React application. Your users are happy with the newfound speed of their application. Time to celebrate!

I am using create-react-app, which uses Webpack. If I run npm run build after implementing code splitting, I can see that Webpack is creating different bundles now.

Our new bundles

More files, but smaller files. And that’s the point 😉

Hope it was clear enough. If not, as always, don’t hesitate to ask questions in the comments.

Uncategorized

Should remote workers be paid differently based on location?

New World Order

With the COVID-19 crisis, one trend has gained a lot of momentum: remote working. A lot of workers were asking for it for quite some time, pressing their companies to allow them to work from anywhere and trust them that they could be more productive on their own terms.

The coronavirus forced their hands obviously and now some companies decided that remote working was worth it. Twitter announced their teams can keep working from home “forever”. Facebook also started the transition towards allowing more of their employees to work remotely.

These two are just some examples of how the crisis help the work from home movement gain traction. Of course, how we do remote work in this crisis is another subject entirely. For hundred of thousands of people, the change was not prepared, or even not wanted. In this configuration, we are trying to make remote work function, during a crisis. But that’s another debate.

What about the salary?

Our good friend Zucky is basically saying Facebook will not pay employees the same based on their location. There are no details yet of what will be done, and how. But it begs the question

SHOULD REMOTE WORKERS SALARIES DIFFER BASED ON THEIR LOCATION?

Assuming two developers with the same skills, experience and productivity. One lives in New York, the other lives in Marrakech. As a CEO, should you adapt the salary of the developer living in New York, because the cost of living will be much higher than in Morocco?

Basecamp, a company with most of their employees working from home, pays their employees based on same base, which I believe is the New York market. Doesn’t matter where they work from. Same experience? Same job? Same pay, period.

If you are a Facebook worker in California, you will be payed higher than a Facebook worker in London. And that disparity will continue after the coronavirus crisis ends and Facebook moves to a remote friendly environment.

What do you think? On one end, if two developers have the same position, they should be able to claim the same compensation for the same work. Should we include the environment they live in in that compensation? A worker in San Francisco is most likely to spend a good amount of his salary to pay a rent. While the developer in Morocco will most likely spend a smaller percentage of his salary towards her housing.

But then, if you start with housing, where do you stop? Should you consider the size of the employee’s family? If they still want to work at the office from time to time or full time, should you compensate the salary for the commute costs?

This is a difficult issue, with quite a lot of nuances. Personally, I quite like the “Basecamp” way: pick a fair location and adapt your salaries based on that location.

I’d love to know where you stand on this issue 😄

Uncategorized

Understanding Prototypes and Inheritance in Javascript

Trying to explain simply a confusing concept.

Introduction

Aaaaah, prototypes… How many blog posts did you read where prototypes are listed as a must-know characteristic of the language? How many times senior developers told you about prototypal inheritance? I’ve spent quite some time avoiding to learn more deeply about this thing. I got tired of procrastinating, so I wrote this thing.

Simple words please… with examples?

Objects in Javascript have an internal property ( in the specification called [[Prototype]] ). This internal property is a reference to another object. Quick example:

// A simple object
const myObject = {
  a: 2,
};
console.log(myObject.a); // 2

// We link newObject to myObject with Object.create
const newObject = Object.create(myObject);

console.log(newObject); // {}
console.log(newObject.a); // 2 ??? Why?

Object.create creates a new object. It takes another object as an argument. The common way to think about what is happening is ( the classical way ) : I made a copy of this object. Well, no.

As you can see, newObject is empty. Object.create takes a prototype as its argument. Which means, we didn’t copy, we linked newObject to myObjectmyObject becomes a prototype of newObject. To know what is inside the prototype of an object, you can use **proto**.

console.log(newObject.__proto__); // { a: 2 }
console.log(myObject.isPrototypeOf(newObject)); // true

Chains have links, [[Prototype]] is a chain. So how does Javascript uses prototypes to retrieve values?

Up the chain… one link at a time.

const original = {
  a: 2,
};

const secondComing = Object.create(original);

const thirdLink = Object.create(secondComing);

console.log(thirdLink); // {}
console.log(secondComing); // {}

console.log(secondComing.isPrototypeOf(thirdLink)); // true
console.log(original.isPrototypeOf(thirdLink)); // true
console.log(thirdLink.isPrototypeOf(original)); // false

console.log(thirdLink.a); // 2

Here is how your favourite language works: it tries to get the property a in the thirdLink object. Can’t find it. Does it return undefined or a error? Nope, it looks in the prototype chain for a link. It finds out that secondComing is a prototype of thirdLink. It looks for a, still can’t find it. It moves on to another link, called original. Finds a = 2 !!

What if I change something in the bottom of the chain?

  • How will it affect the top of the chain? Such a great question.

I decide to change the value a in thirdLink directly:

thirdLink.a = 3;

console.log(thirdLink); //{ a: 3 }
console.log(thirdLink.a); // 3
console.log(original.a); // 2

This is what we call a shadowed property. The new a value shadows the other a values present in the higher prototypes.

What if I want some ice on it?

What if the property in the top link can’t be overwritten?

// Freeze the original, properties can't be changed
Object.freeze(original);
original.a = 3;
// a is still equal to 2
console.log(original); // { a: 2 }

// That will NOT change the value, or shadow it.
thirdLink.a = 3;
console.log(thirdLink); // {}
console.log(thirdLink.a); // 2

Nothing changed because the prototype’s property a is read-only.

However, if you need to change the property value anyway when it is read-only. You must use Object.defineProperty:

// Freeze the original, properties can't be changed
Object.freeze(original);

// Ok, this will work.
Object.defineProperty(thirdLink, "a", { value: 5 });

console.log(thirdLink.a); // 5

So, whenever you think you are changing a value in a object, you must account for the prototypes up the chain. They may have properties with the same name that cant be overwritten in a certain way.

What does it mean for functions?

In a class oriented language, you can create different instances of a class. You copy the class behavior into an object. And this is done again every time you instantiate a class.

In Javascript, however, there are no classes, just objects. The class keyword is only a syntax thing, it doesn’t bring anything class-y to the table. Whatever you can do with the class keyword in ES6, you could do without a problem in ES5.

By default, every function gets a prototype property.

function hello() {
  return "Hello World";
}

function goodBye() {
  return "Goodbye";
}

console.log(hello.prototype); // hello {}
console.log(goodBye.prototype); // goodBye {}

Ok, so what happens if you don’t copy like class-oriented languages? You create multiple objects with a [[Prototype]] link. Like so:

const a = new hello();
const b = new hello();
const c = new goodBye();
const d = new goodBye();

console.log(Object.getPrototypeOf(a) === hello.prototype); // true
console.log(Object.getPrototypeOf(b) === hello.prototype); // true
console.log(Object.getPrototypeOf(c) === goodBye.prototype); // true
console.log(Object.getPrototypeOf(d) === goodBye.prototype); // true

All our objects link to the same hello.prototype or goodBye.prototype origin. So, our objects ( a, b, c and d ) are not completely separated from one another, but linked to the same origin. So, if I add a method in hello.prototypea and b will have access to it, because Javascript will go up the chain to find it. But, I didn’t change anything about a and b:

// I'm not touching a or b
hello.prototype.sayHowDoYouDo = () => {
  console.log("How do you do?");
};

a.sayHowDoYouDo(); // How do you do?
b.sayHowDoYouDo(); // How do you do?

By NOT copying objects but linking them, Javascript doesn’t need to have the entire object environment carried in each object. It just goes up the chain.

Let’s now make the goodBye.prototype a prototype of hello.prototype:

// Objects not linked yet => Errors
c.sayHowDoYouDo(); // Error: not a function
d.sayHowDoYouDo(); // Error: not a function

// This is a ES6 method. First argument will be the link at the bottom of the prototype chain, the second is the top link.
Object.setPrototypeOf(goodBye.prototype, hello.prototype);

// Now, c and d will look up the chain!
c.sayHowDoYouDo(); // How do you do?
d.sayHowDoYouDo(); // How do you do?

Prototypal inheritance

And that, my dear friends, is the concept of prototypal inheritance. Now, I am not a huge fan of the word inheritance here. It would imply some sort of copying, or parent-child relationship, and Javascript doesn’t do that. I have seen the word delegation to describe this, I like it better. Again, Javascript doesn’t natively copy objects, it links them to one another.

I see you waiting for some examples:

function Mammal(type) {
  this.type = type;
  this.talk = () => {
    console.log("Hello friend");
  };
}

Mammal.prototype.myType = function () {
  return this.type;
};

function Dog(name, type) {
  // This next line makes Mammal a prototype of the Dog object
  Mammal.call(this, type);
  this.name = name;
  this.woof = () => {
    console.log("Woof!");
  };
}

// Link the Dog prototype to the Mammal prototype
Object.setPrototypeOf(Dog.prototype, Mammal.prototype);
//OR
// Dog.prototype = Object.create(Mammal.prototype)

Dog.prototype.myName = function () {
  return this.name;
};

const Joe = new Dog("Joe", "Labrador");

Joe.woof(); // Woof!

// myName() function is in the Dog prototype.
console.log(Joe.myName()); // Joe

// myType is in the Mammal prototype.
// Joe is a Dog instance, and Mammap is a prototype of Dog.
console.log(Joe.myType()); // Labrador

// talk() is a method in the Mammal function, which is a prototype of the Joe object.
Joe.talk(); // Hello friend

It also works with objects, obviously. Quick example:

const SuperHero = {
  statement: function () {
    return "I am an anonymous superhero";
  },
};

// SuperHero becomes a prototype of Batman.
const Batman = Object.create(SuperHero);

Batman.statement(); // 'I am an anonymous superhero'

Conclusion

Classical inheritance is a parent-child relationship. It goes from top to bottom. Javascript has prototypal delegation. Although it resembles the classical inheritance, it’s quite different. Objects are linked together, not copied. The references are more from bottom to top.

Prototypes also helps with memory management because you don’t need to carry the whole object environment every time you create a new child object. Everything that needs to be in common can exist in a prototype, therefore being referenced only once.

Tell me what you think about this, I hope I’ve been clear enough.