Using Typescript with React and Redux

Using Typescript with React and Redux

Redux with Typescript. Step 1: Typing the Store. Firstly, we will want to define an interface for our Redux store. Step 2: Defining action types and actions. Action types can be defined using a const & type pattern. Step 3: Defining Reducers. Step 4: Creating the initial Store.

Supercharge the stability of your React apps, with Typescript

Typescript is in its strongest position ever for making your React apps more stable, readable and manageable. The package has been steadily introducing more support for React and Javascript front-end frameworks; features have been ramping up specifically for them since version 3.0 and 3.1. Integration with React used to be a headache-inducing task, but is now a straight forward process that we will talk through in this article.

Create React App now has Typescript support built into the package, since react-scripts 2.1. It can simply be included in a new project with the --typescript flag. We will specifically be using CRA for bootstrapping a React based app with Typescript, before exploring how to integrate types and interfaces into React props and state, followed by a Redux setup.

To read more about Typescript, why it is used and its capabilities, take a look at my Typescript with NodeJS article, that aims to introduce the package and provide integration steps for NodeJS

Installing Create React App with Typescript

The Create React App website has a dedicated page specifically for documenting the installation process as well as migration steps for adding Typescript support for existing apps. To create a new app with Typescript included, run the following:

yarn create react-app app_name --typescript

#or
npx create-react-app app_name --typescript

There are a couple of noticeable changes from the Javascript based CRA boilerplate:

  • Included now is a tsconfig.json file configuring the Typescript compiler options.
  • .js files are now .tsx files. The Typescript compiler will pick up all .tsxfiles at compile time.
  • package.json contains dependencies for @types packages, including support for node, jest, react and react-dom out of the box.
  • react-app-env.d.ts file to reference react-scripts types. This file is automatically generated upon starting the development server, with yarn start.

Running yarn start at this stage will compile and run your app, yielding the identical bootstrapped app in your browser to the original Javascript-only Create React App counterpart.

Before we continue, it is worth stopping the development server and revisiting some linting tools specifically for Typescript and React development. I will be focusing on Sublime Text 3 — being my IDE of choice — but the general concepts of linting apply to all IDEs. Let’s briefly explore the tools.

Installing TSLint-React

Installing linting tools are extremely helpful with Typescript and React; you will find yourself referring to tooltips to obtain a certain type, especially with events. The linting tools are extremely strict with their default setup, so we will omit some of these rules in the installation procedure.

Note: These tools are installed via NPM or Yarn and are not tied to a specific IDE. We will firstly install these tools before the specific packages for Sublime Text 3.

Install typescript,tslint and tslint-react packages globally:

yarn global add tslint typescript tslint-react

Now inside your project directory, initialise tslint:

tslint --init

This command will generate a tslint.json file with some default options. Replace this file with the following:

{
"defaultSeverity": "error",
"extends": [
"tslint-react"
],
"jsRules": {
},
"rules": {
"member-access": false,
"ordered-imports": false,
"quotemark": false,
"no-console": false,
"semicolon": false,
"jsx-no-lambda": false
},
"rulesDirectory": [
],
"linterOptions": {
"exclude": [
"config//*.js",
"node_modules/
/*.ts"
]
}
}

To summarise what is happening in this file:

  • defaultSeverity is the level at which errors will be treated. error being the default value will yield red errors within your IDE, whereas warningwould display orange warnings.
  • "extends": ["tslint-react"]: The rules we are extending from are soley React based — we have removed the tslint-recommended library, some rules of which do not adhere to React syntax.
  • "rules": { "rule-name": false, ...}: We can omit rules in the rulesblock. For example, omiting the member-access rule will stop tslint from reporting that we are missing access types from our functions, (public, private…) — syntax that is not commonly used in React. Another example, ordered-imports, prompts us to order our import statements alphabetically. Check out all the rules available here.
  • "linterOptions": {"exclude": [...]}: Here we are excluding all Javascript files in the config directory and Typescript files within node_modules from TSLint checking.
Sublime Text 3 Packages

As the final step for setting up the development environment, install the SublimeLinter followed by SublimeLinter-tslint packages via PackageControl. Upon restarting Sublime Text the tools will be readily available.

Note: You may receive an error to say that the tslint module was not found upon restarting Sublime Text. If this was the case, re-install the packages locally rather than globally, that we opted for (and what documentation suggests) previously:

yarn add tslint tslint-react

VS Code Extension

For the Visual Studio Code editor, install the TSLint extension for full Typescript support.

With your IDE now ready to handle Typescript development, let’s dive into some code, visiting how to add interfaces and types to props and state within React.

Interfaces and Types for Props and State

We can apply interfaces and types for our props and state of our components.

Defining interfaces

Applying an interface to components will force us to adhere to such data structures when passing props into a component, ensuring that they are all accounted for while also stopping unwanted props to be passed down.

Interfaces can be defined outside of a component or imported from a separate file. Define an interface like so:

interface FormProps {
first_name: string;
last_name: string;
age: number;
agreetoterms?: boolean;
}

Here I have created a FormProps interface consisting of a few values. agreetoterms is optional, hence the ? after the name. We can also apply an interface for state:

interface FormState {
submitted?: boolean;
full_name: string;
age: number;
}

Note: Tslint used to prompt us to use a capital i in front of all our interface names, e.g. IFormProps and IFormState would be the above names. However, it is no longer enforced by default.

Applying interfaces to components

We can apply interfaces to both class components and stateless function components. For class components we utilise angle bracket syntax to apply our props and state interfaces respectively:

export class MyForm extends React.Component<FormProps, FormState> {
...
}

Note: In the event you have no props but would like to define state, you can place either {} or object in place of FormProps. Both values are valid empty objects.

And with function components we can pass our props interface, followed by any other arguments and their specific interfaces:

function MyForm(props: FormProps) {
...
}

Importing interfaces

Defining groups of interface definitions in one file is good practice; a common convention is to create a src/types/ folder with groups of your interfaces:

// src/types/index.tsx

export interface FormProps {
first_name: string;
last_name: string;
age: number;
agreetoterms?: boolean;
}

And to import your needed interfaces into your component files:

// src/components/MyForm.tsx

import React from 'react';
import { StoreState } from '../types/index';
...

Working with enums

Enums are another useful feature of Typescript. Lets say I wanted to define an enum for the MyForm component, and then check whether the submitted form value is valid:

// define enum
enum HeardFrom {
SEARCH_ENGINE = "Search Engine",
FRIEND = "Friend",
OTHER = "Other"
}
//construct heardFrom array
let heardFrom = [HeardFrom.SEARCH_ENGINE,
HeardFrom.FRIEND,
HeardFrom.OTHER];

//get submitted form value
const submitted_heardFrom = form.values.heardFrom;

//check if value is valid
heardFrom.includes(submitted_heardFrom)
? valid = true
: valid = false;

Working with iterables

We can also loop through iterables using for…of and for…in methods in Typescript. These two methods have one key difference:

  • Looping using for…of will return a list of values being iterated.
  • Looping using for…in will return a list of keys being iterated.
for (let i in heardFrom) {
console.log(i); // "0", "1", "2",
}

for (let i of heardFrom) {
console.log(i); // "Search Engine", "Friend", "Other"
}

Typing Events

In the event (no pun intended) you wish to type events, such as onChange or onClick events, utilise your syntax tools to obtain the exact event you need.

Consider the following example, where we update our state every time a name input is changed. By hovering your mouse over handleChange(), we can see clearly that the event type is indeed React.ChangeEvent<HTMLInputElement>:

Hovering over handleChange() to obtain the event type

This type is then used when typing the e argument in our handleChangefunction definition.

I have also typed the name and value objects of e with the following syntax:

const {name, value}: {name: string; value: string;} = e.target;

If you do not know what types an object specifies, then you can simply use the any type. We could have done this here:

const {name, value}: any = e.target;

Now we have covered some basics, we will next visit how to set up Redux with Typescript, and review more Typescript specific features along the way.

Redux with Typescript

If you would like to familiarise yourself with how Redux works with React, check out my introductory article:

Step 1: Typing the Store

Firstly, we will want to define an interface for our Redux store. Defining the expected state structure will be beneficial for your team and aid in maintaining the expected app state.

This can be done within the /src/types/index.tsx file we discussed earlier. Here is an example that deals with locality and authentication:

// src/types/index.tsx

export interface MyStore {
language: string;
country: string;
auth: {
authenticated: boolean;
username?: string;
};
}

Step 2: Defining action types and actions

Action types can be defined using a const & type pattern. We will firstly want to define the action types within a src/constants/index.tsx file:

// src/constants/index.tsx

export const SET_LANGUAGE = 'INCREMENT_ENTHUSIASM';
export type SET_LANGUAGE = typeof SET_LANGUAGE;
export const SET_COUNTRY = 'SET_COUNTRY';
export type SET_COUNTRY = typeof SET_COUNTRY;
export const AUTHENTICATE = 'AUTHENTICATE';
export type AUTHENTICATE = typeof AUTHENTICATE;

Notice how the constants we just defined are used as an interface type andas a string literal, which we will utilise next.

These const & type objects can now be imported into your src/actions/index.tsx file, where we can define action interfaces and the actions themselves, and typing them along the way:

// src/actions/index.tsx

import * as constants from '../constants';
//define action interfaces
export interface SetLanguage {
type: constants.SET_LANGUAGE;
language: string;
}
export interface SetCountry {
type: constants.SET_COUNTRY;
country: string;
}
export interface Authenticate{
type: constants.AUTHENTICATE;
username: string;
pw: string;
}
//define actions
export function setLanguage(l: string): SetLanguage ({
type: constants.SET_LANGUAGE,
language: l
});
export function setCountry(c: string): SetCountry ({
type: constants.SET_COUNTRY,
country: c
});
export function authenticate(u: string, pw: string): Authenticate ({
type: constants.SET_COUNTRY,
username: u,
pw: pw
});

Check out the authenticate action in particular here — we are passing a username and password, both of which are of type string, into the function. The return value is also typed, in this case as Authenticate.

Within the Authenticate interface we are also including the expected username and pw values for the action to be valid.

Step 3: Defining Reducers

To simplify the process of specifying an action type within a reducer, we can take advantage of union types, introduced in Typescript 1.4. A union type gives us the ability to combine 2 more more types into one type.

Back in our actions file, add a union type for locality under our interfaces:

// src/actions/index.tsx

export type Locality = SetLanguage | SetCountry;

Now we can apply this Locality type to our locality reducer action, in bold text below:

// src/reducers/index.tsx

import { Locality } from '../actions';
import { StoreState } from '../types/index';
import { SET_LANGUAGE, SET_COUNTRY, AUTHENTICATE} from '../constants/index';
export function locality(state: StoreState, action: Locality): StoreState {

switch (action.type) {
case SET_LANGUAGE:
return return { ...state, language: action.language};
case SET_COUNTRY:
return { ...state, language: action.country};
case AUTHENTICATE:
return {
...state,
auth: {
username: action.username,
authenticated: true
}
};
}
return state;
}

This reducer is relatively straight forward, but nonetheless fully typed:

  • This reducer, named locality, is typing our state as StoreState, and the expected action as a Locality type.
  • The reducer will return a StoreState object, if only just the original state in the event no actions are matched.
  • Our constant & type pairs are being utilised here too, as a means to switch between actions.

Step 4: Creating the initial Store

Now within your index.tsx we can initiate the store, utilising angle brackets again to pass the type in conjunction with createStore():

// src/index.tsx

import { createStore } from 'redux';
import { locality } from './reducers/index';
import { StoreState } from './types/index';
const store = createStore<StoreState>(locality, {
language: 'British (English)',
country: 'United Kingdom',
auth: {
authenticated: false
}
});

We are almost done — this covers most of our Redux integration. Let’s also visit mapStateToProps and mapDispatchToProps to cater for your container components.

Mapping State and Dispatch

Within mapStateToProps, remember to map the state argument with StoreState. The second argument, ownProps, can also be typed with a props interface:

// mapStateToProps example

import { StoreState } from '../types/index';
interface LocalityProps = {
country: string;
language: string;
}
function mapStateToProps (state: StoreState, ownProps: LocalityProps) ({
language: state.language,
country: state.country,
});

mapDispatchToProps is slightly different; we are utilising angle brackets again to pass an interface into the Dispatch method. Then, as expected, the return block dispatches our Locality type actions:

// mapDispatchToProps example

const mapDispatchToProps = {
actions.setLanguage,
actions.setCountry
}

Note: As we are wrapping these actions within connect(), it is not required to wrap our actions within dispatch(). We can also emit the parameters of our actions here.

Lastly, we can connect the two to our presentation component:

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
In Summary

This article has introduced Typescript in conjunction with React and how to utilise tslint-react for smoother development. We have visited how to interface and type your props and state throughout your components, as well as how to handle Typescript with events. Finally, we visited Typescript integration with Redux, integrating types throughout a Redux setup.

From here, you are now well placed to study the full feature set of Typescript in the official documentation.

Typescript does introduce additional consideration into your React projects, but the additional investment of supporting the language will ultimately improve the manageability of your apps as they scale.

Modularity and compartmentalising code is promoted by using Typescript; traits that medium to larger sized projects will want to adhere to. Keep this in mind as your projects grow: If you are finding maintainability a problem, Typescript could be the answer to improve readability while reducing the probability of errors throughout your codebase.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

Originally published on medium.com

JavaScript developers should you be using Web Workers?

JavaScript developers should you be using Web Workers?

Do you think JavaScript developers should be making more use of Web Workers to shift execution off of the main thread?

Originally published by David Gilbertson at https://medium.com

So, Web Workers. Those wonderful little critters that allow us to execute JavaScript off the main thread.

Also known as “no, you’re thinking of Service Workers”.

Photo by Caleb Jones on Unsplash

Before I get into the meat of the article, please sit for a lesson in how computers work:

Understood? Good.

For the red/green colourblind, let me explain. While a CPU is doing one thing, it can’t be doing another thing, which means you can’t sort a big array while a user scrolls the screen.

This is bad, if you have a big array and users with fingers.

Enter, Web Workers. These split open the atomic concept of a ‘CPU’ and allow us to think in terms of threads. We can use one thread to handle user-facing work like touch events and rendering the UI, and different threads to carry out all other work.

Check that out, the main thread is green the whole way through, ready to receive and respond to the gentle caress of a user.

You’re excited (I can tell), if we only have UI code on the main thread and all other code can go in a worker, things are going to be amazing (said the way Oprah would say it).

But cool your jets for just a moment, because websites are mostly about the UI — it’s why we have screens. And a lot of a user’s interactions with your site will be tapping on the screen, waiting for a response, reading, tapping, looking, reading, and so on.

So we can’t just say “here’s some JS that takes 20ms to run, chuck it on a thread”, we must think about where that execution time exists in the user’s world of tap, read, look, read, tap…

I like to boil this down to one specific question:

Is the user waiting anyway?

Imagine we have created some sort of git-repository-hosting website that shows all sorts of things about a repository. We have a cool feature called ‘issues’. A user can even click an ‘issues’ tab in our website to see a list of all issues relating to the repository. Groundbreaking!

When our users click this issues tab, the site is going to fetch the issue data, process it in some way — perhaps sort, or format dates, or work out which icon to show — then render the UI.

Inside the user’s computer, that’ll look exactly like this.

Look at that processing stage, locking up the main thread even though it has nothing to do with the UI! That’s terrible, in theory.

But think about what the human is actually doing at this point. They’re waiting for the common trio of network/process/render; just sittin’ around with less to do than the Bolivian Navy.

Because we care about our users, we show a loading indicator to let them know we’ve received their request and are working on it — putting the human in a ‘waiting’ state. Let’s add that to the diagram.

Now that we have a human in the picture, we can mix in a Web Worker and think about the impact it will have on their life:

Hmmm.

First thing to note is that we’re not doing anything in parallel. We need the data from the network before we process it, and we need to process the data before we can render the UI. The elapsed time doesn’t change.

(BTW, the time involved in moving data to a Web Worker and back is negligible: 1ms per 100 KB is a decent rule of thumb.)

So we can move work off the main thread and have a page that is responsive during that time, but to what end? If our user is sitting there looking at a spinner for 600ms, have we enriched their experience by having a responsive screen for the middle third?

No.

I’ve fudged these diagrams a little bit to make them the gorgeous specimens of graphic design that they are, but they’re not really to scale.

When responding to a user request, you’ll find that the network and DOM-manipulating part of any given task take much, much longer than the pure-JS data processing part.

I saw an article recently making the case that updating a Redux store was a good candidate for Web Workers because it’s not UI work (and non-UI work doesn’t belong on the main thread).

Chucking the data processing over to a worker thread sounds sensible, but the idea struck me as a little, umm, academic.

First, let’s split instances of ‘updating a store’ into two categories:

  1. Updating a store in response to a user interaction, then updating the UI in response to the data change
  2. Not that first one

If the first scenario, a user taps a button on the screen — perhaps to change the sort order of a list. The store updates, and this results in a re-rendering of the DOM (since that’s the point of a store).

Let me just delete one thing from the previous diagram:

In my experience, it is rare that the store-updating step goes beyond a few dozen milliseconds, and is generally followed by ten times that in DOM updating, layout, and paint. If I’ve got a site that’s taking longer than this, I’d be asking questions about why I have so much data in the browser and so much DOM, rather than on which thread I should do my processing.

So the question we’re faced with is the same one from above: the user tapped something on the screen, we’re going to work on that request for hopefully less than a second, why would we want to make the screen responsive during that time?

OK what about the second scenario, where a store update isn’t in response to a user interaction? Performing an auto-save, for example — there’s nothing more annoying than an app becoming unresponsive doing something you didn’t ask it to do.

Actually there’s heaps of things more annoying than that. Teens, for example.

Anyhoo, if you’re doing an auto-save and taking 100ms to process data client-side before sending it off to a server, then you should absolutely use a Web Worker.

In fact, any ‘background’ task that the user hasn’t asked for, or isn’t waiting for, is a good candidate for moving to a Web Worker.

The matter of value

Complexity is expensive, and implementing Web Workers ain’t cheap.

If you’re using a bundler — and you are — you’ll have a lot of reading to do, and probably npm packages to install. If you’ve got a create-react-app app, prepare to eject (and put aside two days twice a year to update 30 different packages when the next version of Babel/Redux/React/ESLint comes out).

Also, if you want to share anything fancier than plain data between a worker and the main thread you’ve got some more reading to do (comlink is your friend).

What I’m getting at is this: if the benefit is real, but minimal, then you’ve gotta ask if there’s something else you could spend a day or two on with a greater benefit to your users.

This thinking is true of everything, of course, but I’ve found that Web Workers have a particularly poor benefit-to-effort ratio.

Hey David, why you hate Web Workers so bad?

Good question.

This is a doweling jig:

I own a doweling jig. I love my doweling jig. If I need to drill a hole into the end of a piece of wood and ensure that it’s perfectly perpendicular to the surface, I use my doweling jig.

But I don’t use it to eat breakfast. For that I use a spoon.

Four years ago I was working on some fancy animations. They looked slick on a fast device, but janky on a slow one. So I wrote fireball-js, which executes a rudimentary performance benchmark on the user’s device and returns a score, allowing me to run my animations only on devices that would render them smoothly.

Where’s the best spot to run some CPU intensive code that the user didn’t request? On a different thread, of course. A Web Worker was the correct tool for the job.

Fast forward to 2019 and you’ll find me writing a routing algorithm for a mapping application. This requires parsing a big fat GeoJSON map into a collection of nodes and edges, to be used when a user asks for directions. The processing isn’t in response to a user request and the user isn’t waiting on it. And so, a Web Worker is the correct tool for the job.

It was only when doing this that it dawned on me: in the intervening quartet of years, I have seen exactly zero other instances where Web Workers would have improved the user experience.

Contrast this with a recent resurgence in Web Worker wonderment, and combine that contrast with the fact that I couldn’t think of anything else to write about, then concatenate that combined contrast with my contrarian character and you’ve got yourself a blog post telling you that maybe Web Workers are a teeny-tiny bit overhyped.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

An Introduction to Web Workers

JavaScript Web Workers: A Beginner’s Guide

Using Web Workers to Real-time Processing

How to use Web Workers in Angular app

Using Web Workers with Angular CLI