10 Weeks of React: Week 2

Arvin Behshad
7 min readApr 9, 2017

--

Moving onto React Native

Deliverables this week

The politics of JavaScript

Fair warning: this ‘rant’ could be an article in itself, so if you just want to read about React, feel free to scroll to the next heading.

I’d like to begin this week’s story by looking back at the infamous article How it feels to learn JavaScript in 2016. I remember reading it when it came out and feeling utterly hopeless, yet up for the challenge.

Until recently, I had always kept a distance from JavaScript apart from the occasional jQuery quick-fix because I honestly couldn’t keep up with all the noise in the community. It seemed like a lost cause.

Today I feel very different. What I’ve learnt in the last couple of months, both through courses like #JavaScript30 but also in the past two weeks learning React has completely changed my mind. It’s not that there’s a lack of solutions, it’s that there’s too many. JavaScript might just be the most un-opinionated language out there, and it has resulted in a stigmatization by people like me and most of my peers who just don’t know any better.

This democracy is both good and bad — for beginners it’s mostly bad. If JavaScript wasn’t such a popular language and hadn’t gained the de-facto title language of the web I probably would never have chosen to learn it.

The reality when starting a JavaScript project today

This image captures the reason that I would stay away from JavaScript in the past. There just aren’t any standardized methods or established best practices across the language, which is probably the most important requirement for a beginner of any language to have. Beginners need some strict guidelines and conventions to rest their uncertainties upon, which JavaScript provides all too many opinions about.

This is not so surprising after I learnt that the language was initially created in just 10 days. But even attempts to form standards don’t succeed (honorable mention to JavaScript Standard Style) because apparently semicolons are still a topic of discussion in 2017.

JavaScript is ever-changing at a speed that only devoted people can keep up with (i.e. definitely not for conservative Java Enterprise programmers). There’s a reason why npm, JavaScripts package manager, is the world’s largest software registry. React and other JavaScript libraries have to embrace this rapid change by also being completely un-opinionated, open to third party add-ons and libraries. So in a sense the language has infinite growth and as a result there’s just too much noise to keep up with.

Anyway…back to React.

Diving head first into React Native

The setup on my Ubuntu machine was much more complicated than I expected. Definitely 👎 to that, Facebook. I imagine the only case where the setup runs seamlessly is on a Mac when developing for iOS.

Following the official guide only gets you part of the way there. I kept getting this random error (at least it’s beautiful). I discovered that I need to run a development server alongside my app. The easiest way to do so is to run the development server with react-native start — then running my app in another tab with react-native run-android

The prettiest stack trace you’ve ever seen

I’m also pleasantly surprised that I can run my app from Android Studio, even though I like to write my code separately in Sublime Text.

React is very similar to React Native

The main difference is that web elements are replaced with app components, effectively influencing the way you think about the View. I’m glad they’ve managed to bridge the gap between mobile and web. Their paradigm remains consistent. All you have to do is to have some experience developing native app views.

The project is well structured and after learning React for a week I had no problems picking up the official documentation and accompanying tutorial. This also explains why some have been curious to build OSX and Windows desktop apps using the React paradigm.

Hot Reloading

Hot Reloading is easily the best thing about React Native. You no longer have to recompile the entire app on every small change. Since everything in React is based on modular components, React just has to recompile the individual components that have been updated. It does this by hot reloading, which means that it is fast enough to serve you your updated app every single time you hit save. This changes everything!

This joke is deprecated with the release of hot reloading

“What’s the catch?”, you might ask. Hot reloading doesn’t update the app’s state. You have to reload manually which is still pretty fast. I learnt this the hard way, by spending 40 minutes scratching my head over why initialName is null in a case like this:

More ES6

I spent a day learning ES6 and refactoring my finished React website to reflect the differences. I was definitely cherry picking, leaving what I didn’t like. I’ll explain why.

Implications for React

With ES6, React acts less like a scripting language and more like an Object-Oriented language utilizing classes. You might recall that I was celebrating the move away from OOP last week, but I see it as React finding a middle-ground, taking the best of both worlds, and more importantly leaving it up to the developer.

One of the most notable cases of using ES6 in your React project is that you no longer use React.createClass — instead you create a class which extends the React.Component class. The best consequence here is that there’s finally a constructor, so I can stop referring to getInitialState() as “it’s kinda like a constructor”.

React, before and after ES6 classes

Arrow Functions and the ensuing magic

I talked about this very briefly last week because I was first introduced to the paradigm when I learned about higher-order functions in my Erlang course. In essence, arrow functions are a much better way of expressing functions in JavaScript. This makes it highly relevant for a language where almost everything is a function. You have functions tied to variables, functions in objects, functions as arguments to other functions and even functions within functions…within more functions.

I watched a great tutorial by this goofy Swedish guy and afterwards I really just wanted to re-write everything as one-liner arrow functions. It’s so magical how you can achieve more with less.

Just to provide a TL;DR of the video: Let’s say you have a log of all events involving your dragon character in the dragonEvents object below and you want to calculate the total damage done to target player-dorkman . This is done by filtering out the events of type attack performed on said target from the log and taking the sum of the values.

More than anything, notice how much cleaner the last snippet is. This used to be one of the biggest grudges I held towards JavaScript and the source of many bugs, learning setbacks and ESLint frustrations. My eyes simply aren’t trained to navigate around triple-nested curly brackets.

The deal-breaker

I’ve decided not to switch over to ES6 classes in my first React project, mainly due to one big factor: Binding this. It seems like the jury’s still out on the best practices.

React used to autobind ‘this’

If you use React.createClass, React auto-binds all functions to this. So the this keyword is bound to your component’s instance automatically:

// This magically works with React.createClass
// because `this` is bound for you.
onChange={this.handleClick}

There are many alternative ways of handling this, all from using arrow functions to importing 3rd party libraries which let you insert@autobind annotations.

In the official docs, Facebook currently recommends binding in the constructor. Even though I know that React.createClass is not the way to go as it’s already extracted from React core in the latest release. As with everything in JavaScript, I’m patiently waiting for the noise to die down.

constructor(props) {
super(props);
this.state = {isToggleOn: true};
//This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}

New insights to React

The only gotcha with modular components

React has proven that there are so many advantages to building an app using modular components. However, naturally, it has one big annoying downside when it comes to components sharing data and functions.

A component’s state is passed down to other components using props. Let’s take the example of App.js (the main component) passing down five properties to the Inventory component.

render: function () {
return (
<Inventory fishes={this.state.fishes}
addFish={this.addFish}
loadSamples={this.loadSamples}
linkState={this.linkState}
removeFish={this.removeFish}
/>
)
}

Inside Inventory.js, you can then access the fishes object with this.props.fishes . However, you can imagine how cumbersome this becomes to maintain if you want to send data past Inventory, three or four levels down.

The way to do this is by using a spread. By passing {...this.props} to a component you pass it the entire props object from its parent, effectively allowing it to inherit all props. The downside is naturally that one will be tempted to do this every time.

How to set state

In React you have to explicitly specify when you want to commityour changes to the state by running this.setState({ key : this.state.data }) after specifying the actual changes. This might seem redundant at first, and I was definitely confused, but if we imagine that you’re making several changes it’s much more efficient and preferable to only commit once as oppose to on every change.

Remember, the React magic is that the view renders by running diff on every state change. This means you’ll have render running on every change, which will dramatically affect performance.

To elaborate, it turns out that this.state is asyncronous and should be treated as if it’s immutable. I spent a long time wondering why you would call setState instead of just setting this.state directly. What happens in doing so is that it might introduce very subtle bugs. I’m glad I learned this sooner rather than later :)

Thanks for reading!

Follow @arvinexplores on Instagram and Twitter for more content.

--

--

Arvin Behshad

travel. self-discovery. storytelling. JS⚛ developer exploring the intersection of art and technology.