Diving Deeper into Redux

Diving Deeper into Redux

In this article, I’ll delve into Redux’s state container by building a payroll processing engine. The app will store pay stubs, along with all the extras — such as bonuses and stock options.

In this article, I’ll delve into Redux’s state container by building a payroll processing engine. The app will store pay stubs, along with all the extras — such as bonuses and stock options.

I’ll keep the solution in plain JavaScript with TypeScript for type checking. Since Redux is super testable, I’ll also use Jest to verify the app.

Building stateful modern applications is complex. As state mutates, the app becomes unpredictable and hard to maintain. That’s where Redux comes in. Redux is a lightweight library that tackles state. Think of it as a state machine.

For the purposes of this tutorial, I’ll assume a moderate level of familiarity with JavaScript, Node, and npm.

To begin, you can initialize this app with npm:

npm init 

When asked about the test command, go ahead and put jest. This means npm t will fire up Jest and run all unit tests. The main file will be index.js to keep it nice and simple. Feel free to answer the rest of the npm init questions to your heart’s content.

I’ll use TypeScript for type checking and nailing down the data model. This aids in conceptualizing what we’re trying to build.

To get going with TypeScript:

npm i typescript --save-dev 

I’ll keep dependencies that are part of the dev workflow in devDependencies. This makes it clear which dependencies are for developers and which goes to prod. With TypeScript ready, add a start script in the package.json:

"start": "tsc && node .bin/index.js" 

Create an index.ts file under the src folder. This separates source files from the rest of the project. If you do an npm start, the solution will fail to execute. This is because you’ll need to configure TypeScript.

Create a tsconfig.json file with the following configuration:

{
  "compilerOptions": {
    "strict": true,
    "lib": ["esnext", "dom"],
    "outDir": ".bin",
    "sourceMap": true
  },
  "files": [
    "src/index"
  ]
}

I could have put this configuration in a tsc command-line argument. For example, tsc src/index.ts --strict .... But it’s much cleaner to go ahead and put all this in a separate file. Note the start script in package.json only needs a single tsc command.

Here are sensible compiler options that will give us a good starting point, and what each option means:

  • strict: enable all strict type checking options, i.e., --noImplicitAny, --strictNullChecks, etc.
  • lib: list of library files included in the compilation
  • outDir: redirect output to this directory
  • sourceMap: generate source map file useful for debugging
  • files: input files fed to the compiler

Because I’ll be using Jest for unit testing, I’ll go ahead and add it:

npm i jest ts-jest @types/jest @types/node --save-dev 

The ts-jest dependency adds type checking to the testing framework. One gotcha is to add a jest configuration in package.json:

"jest": {
  "preset": "ts-jest"
}

This makes it so the testing framework picks up TypeScript files and knows how to transpile them. One nice feature with this is you get type checking while running unit tests. To make sure this project is ready, create a __tests__ folder with an index.test.ts file in it. Then, do a sanity check. For example:

it('is true', () => {
  expect(true).toBe(true);
});

Doing npm start and npm t now runs without any errors. This tells us we’re now ready to start building the solution. But before we do, let’s add Redux to the project:

npm i redux --save 

This dependency goes to prod. So, no need to include it with --save-dev. If you inspect your package.json, it goes in dependencies.

Payroll Engine in Action

The payroll engine will have the following: pay, reimbursement, bonus, and stock options. In Redux, you can’t directly update state. Instead, actions are dispatched to notify the store of any new changes.

So, this leaves us with the following action types:

const BASE_PAY = 'BASE_PAY';
const REIMBURSEMENT = 'REIMBURSEMENT';
const BONUS = 'BONUS';
const STOCK_OPTIONS = 'STOCK_OPTIONS';
const PAY_DAY = 'PAY_DAY';

The PAY_DAY action type is useful for dolling out a check on pay day and keeping track of pay history. These action types guide the rest of the design as we flesh out the payroll engine. They capture events in the state lifecycle — for example, setting a base pay amount. These action events can attach to anything, whether that be a click event or a data update. Redux action types are abstract to the point where it doesn’t matter where the dispatch comes from. The state container can run both on the client and/or server.

TypeScript

Using type theory, I’ll nail down the data model in terms of state data. For each payroll action, say an action type and an optional amount. The amount is optional, because PAY_DAY doesn’t need money to process a paycheck. I mean, it could charge customers but leave it out for now (maybe introducing it in version two).

So, for example, put this in src/index.ts:

interface PayrollAction {
  type: string;
  amount?: number;
}

For pay stub state, we need a property for base pay, bonus, and whatnot. We’ll use this state to maintain a pay history as well.

This TypeScript interface ought to do it:

interface PayStubState {
  basePay: number;
  reimbursement: number;
  bonus: number;
  stockOptions: number;
  totalPay: number;
  payHistory: Array;
}

The PayStubState is a complex type, meaning it depends on another type contract. So, define the payHistory array:

interface PayHistoryState {
  totalPay: number;
  totalCompensation: number;
}

With each property, note TypeScript specifies the type using a colon. For example, : number. This settles the type contract and adds predictability to the type checker. Having a type system with explicit type declarations enhances Redux. This is because the Redux state container is built for predictable behavior.

As the app mutates, type checking adds an extra layer of predictability. Type theory also aids as the app scales because it’s easier to refactor large sections of code.

Conceptualizing the engine with types now helps to create the following action functions:

export const processBasePay = (amount: number): PayrollAction =>
  ({type: BASE_PAY, amount});
export const processReimbursement = (amount: number): PayrollAction =>
  ({type: REIMBURSEMENT, amount});
export const processBonus = (amount: number): PayrollAction =>
  ({type: BONUS, amount});
export const processStockOptions = (amount: number): PayrollAction =>
  ({type: STOCK_OPTIONS, amount});
export const processPayDay = (): PayrollAction =>
  ({type: PAY_DAY});

What’s nice is that, if you attempt to do processBasePay('abc'), the type checker barks at you. Breaking a type contract adds unpredictability to the state container. I’m using a single action contract like PayrollAction to make the payroll processor more predictable. Note amount is set in the action object via an ES6 property shorthand. The more traditional approach is amount: amount, which is long-winded. An arrow function, like () => ({}), is one succinct way to write functions that return an object literal.

Reducer as a Pure Function

The reducer functions need a state and an action parameter. The state should have an initial state with a default value. So, can you imagine what our initial state might look like? I’m thinking it needs to start at zero with an empty pay history list.

For example:

const initialState: PayStubState = {
  basePay: 0, reimbursement: 0,
  bonus: 0, stockOptions: 0,
  totalPay: 0, payHistory: []
};

The type checker makes sure these are proper values that belong in this object. With the initial state in place, begin creating the reducer function:

export const payrollEngineReducer = (
  state: PayStubState = initialState,
  action: PayrollAction): PayStubState => {

The Redux reducer has a pattern where all action types get handled by a switch statement. But before going through all switch cases, I’ll create a reusable local variable:

let totalPay: number = 0; 

Note that it’s okay to mutate local variables if you don’t mutate global state. I use a let operator to communicate this variable is going to change in the future. Mutating global state, like the state or action parameter, causes the reducer to be impure. This functional paradigm is critical because reducer functions must remain pure.

Start the reducer’s switch statement to handle the first use case:

switch (action.type) {
  case BASE_PAY:
    const {amount: basePay = 0} = action;
    totalPay = computeTotalPay({...state, basePay});

    return {...state, basePay, totalPay};

I’m using an ES6 rest operator to keep state properties the same. For example, ...state. You can override any properties after the rest operator in the new object. The basePay comes from destructuring, which is a lot like pattern matching in other languages. The computeTotalPay function is set as follows:

const computeTotalPay = (payStub: PayStubState) =>
  payStub.basePay + payStub.reimbursement
  + payStub.bonus - payStub.stockOptions;

Note you deduct stockOptions because the money will go towards buying company stock. Say you want to process a reimbursement:

case REIMBURSEMENT:
  const {amount: reimbursement = 0} = action;
  totalPay = computeTotalPay({...state, reimbursement});

  return {...state, reimbursement, totalPay};

Since amount is optional, make sure it has a default value to reduce mishaps. This is where TypeScript shines, because the type checker picks up on this pitfall and barks at you. The type system knows certain facts so it can make sound assumptions. Say you want to process bonuses:

case BONUS:
  const {amount: bonus = 0} = action;
  totalPay = computeTotalPay({...state, bonus});

  return {...state, bonus, totalPay};

This pattern makes the reducer readable because all it does is maintain state. You grab the action’s amount, compute total pay, and create a new object literal. Processing stock options is not much different:

case STOCK_OPTIONS:
  const {amount: stockOptions = 0} = action;
  totalPay = computeTotalPay({...state, stockOptions});

  return {...state, stockOptions, totalPay};

For processing a paycheck on pay day, it’ll need to blot out bonus and reimbursement. These two properties don’t remain in state per paycheck. And, add an entry to pay history. Base pay and stock options can stay in state because they don’t change as often per paycheck. With this in mind, this is how PAY_DAY goes:

case PAY_DAY:
  const {payHistory} = state;
  totalPay = state.totalPay;

  const lastPayHistory = payHistory.slice(-1).pop();
  const lastTotalCompensation = (lastPayHistory
    && lastPayHistory.totalCompensation) || 0;
  const totalCompensation = totalPay + lastTotalCompensation;

  const newTotalPay = computeTotalPay({...state,
    reimbursement: 0, bonus: 0});
  const newPayHistory = [...payHistory, {totalPay, totalCompensation}];

  return {...state, reimbursement: 0, bonus: 0,
    totalPay: newTotalPay, payHistory: newPayHistory};

In an array like newPayHistory, use a spread operator, which is the reverse of rest. Unlike rest, which collects properties in an object, this spreads items out. So, for example, [...payHistory]. Even though both these operators look similar, they aren’t the same. Look closely, because this might come up in an interview question.

Using pop() on payHistory doesn’t mutate state. Why? Because slice() returns a brand new array. Arrays in JavaScript are copied by reference. Assigning an array to a new variable doesn’t change the underlying object. So, one must be careful when dealing with these types of objects.

Because there’s a chance lastPayHistory is undefined, I use poor man’s null coalescing to initialize it to zero. Note the (o && o.property) || 0 pattern to coalesce. Maybe a future version of JavaScript or even TypeScript will have a more elegant way of doing this.

Every Redux reducer must define a default branch. To make sure state doesn’t become undefined:

default:
  return state;
Testing the Reducer Function

One of the many benefits of writing pure functions is that they’re testable. A unit test is one where you must expect predictable behavior — to the point where you can automate all tests as part of a build. In __tests__/index.test.ts, knock out the dummy test and import all functions of interest:

import { processBasePay,
  processReimbursement,
  processBonus,
  processStockOptions,
  processPayDay,
  payrollEngineReducer } from '../src/index';

Note that all functions were set with an export so you can import them in. For a base pay, fire up the payroll engine reducer and test it:

it('process base pay', () => {
  const action = processBasePay(10);
  const result = payrollEngineReducer(undefined, action);

  expect(result.basePay).toBe(10);
  expect(result.totalPay).toBe(10);
});

Redux sets the initial state as undefined. Therefore, it’s always a good idea to provide a default value in the reducer function. What about processing a reimbursement?

it('process reimbursement', () => {
  const action = processReimbursement(10);
  const result = payrollEngineReducer(undefined, action);

  expect(result.reimbursement).toBe(10);
  expect(result.totalPay).toBe(10);
});

The pattern here is the same for processing bonuses:

it('process bonus', () => {
  const action = processBonus(10);
  const result = payrollEngineReducer(undefined, action);

  expect(result.bonus).toBe(10);
  expect(result.totalPay).toBe(10);
});

For stock options:

it('skip stock options', () => {
  const action = processStockOptions(10);
  const result = payrollEngineReducer(undefined, action);

  expect(result.stockOptions).toBe(0);
  expect(result.totalPay).toBe(0);
});

Note totalPay must remain the same when stockOptions is greater than totalPay. Since this hypothetical company is ethical, is doesn’t want to take money from its employees. If you run this test, note that totalPay is set to -10 because stockOptions gets deducted. This is why we test code! Let’s fix this where it computes total pay:

const computeTotalPay = (payStub: PayStubState) =>
  payStub.totalPay >= payStub.stockOptions
  ? payStub.basePay + payStub.reimbursement
    + payStub.bonus - payStub.stockOptions
  : payStub.totalPay;

If the employee doesn’t make enough money to buy company stock, go ahead and skip the deduction. Also, make sure it resets stockOptions to zero:

case STOCK_OPTIONS:
  const {amount: stockOptions = 0} = action;
  totalPay = computeTotalPay({...state, stockOptions});

  const newStockOptions = totalPay >= stockOptions
    ? stockOptions : 0;

  return {...state, stockOptions: newStockOptions, totalPay};

The fix figures out whether they have enough in newStockOptions. With this, unit tests pass, and the code is sound and makes sense. We can test the positive use case where there’s enough money for a deduction:

it('process stock options', () => {
  const oldAction = processBasePay(10);
  const oldState = payrollEngineReducer(undefined, oldAction);
  const action = processStockOptions(4);
  const result = payrollEngineReducer(oldState, action);

  expect(result.stockOptions).toBe(4);
  expect(result.totalPay).toBe(6);
});

For pay day, test with multiple states and make sure one-time transactions don’t persist:

it('process pay day', () => {
  const oldAction = processBasePay(10);
  const oldState = payrollEngineReducer(undefined, oldAction);
  const action = processPayDay();
  const result = payrollEngineReducer({...oldState, bonus: 10,
    reimbursement: 10}, action);

  expect(result.totalPay).toBe(10);
  expect(result.bonus).toBe(0);
  expect(result.reimbursement).toBe(0);
  expect(result.payHistory[0]).toBeDefined();
  expect(result.payHistory[0].totalCompensation).toBe(10);
  expect(result.payHistory[0].totalPay).toBe(10);
});

Note how I tweak oldState to verify bonus and reset reimbursement back to zero.

What about the default branch in the reducer?

it('handles default branch', () => {
  const action = {type: 'INIT_ACTION'};
  const result = payrollEngineReducer(undefined, action);

  expect(result).toBeDefined();
});

Redux sets an action type like INIT_ACTION in the beginning. All we care about is that our reducer sets some initial state.

Putting It All Together

At this point, you may start to wonder if Redux is more of a design pattern than anything else. If you answer that it’s both a pattern and a lightweight library, then you’re correct. In index.ts, import Redux:

import { createStore } from 'redux'; 

The next code sample can go wrapped around this if statement. This is a stopgap, so unit tests don’t leak into integration tests:

if (!process.env.JEST_WORKER_ID) {
}

I don’t recommend doing this in a real project. Modules can go in separate files to isolate components. This makes it more readable and won’t leak concerns. Unit tests also benefit from the fact modules run in isolation.

Fire up a Redux store with the payrollEngineReducer:

const store = createStore(payrollEngineReducer, initialState);
const unsubscribe = store.subscribe(() => console.log(store.getState()));

Every store.subscribe() returns a subsequent unsubscribe() function useful for cleaning up. It unsubscribes callbacks when actions get dispatched through the store. Here, I’m outputting current state to the console with store.getState().

Say this employee makes 300, has a 50 reimbursement, 100 bonus, and 15 going towards company stock:

store.dispatch(processBasePay(300));
store.dispatch(processReimbursement(50));
store.dispatch(processBonus(100));
store.dispatch(processStockOptions(15));
store.dispatch(processPayDay());

To make it more interesting, do another 50 reimbursement and process another paycheck:

store.dispatch(processReimbursement(50));
store.dispatch(processPayDay());

Finally, run yet another paycheck and unsubscribe from the Redux store:

store.dispatch(processPayDay());

unsubscribe();

The end result looks like this:

{ "basePay": 300,
  "reimbursement": 0,
  "bonus": 0,
  "stockOptions": 15,
  "totalPay": 285,
  "payHistory":
   [ { "totalPay": 435, "totalCompensation": 435 },
     { "totalPay": 335, "totalCompensation": 770 },
     { "totalPay": 285, "totalCompensation": 1055 } ] }

As shown, Redux maintains state, mutates, and notifies subscribers in one sweet little package. Think of Redux as a state machine that is the source of truth for state data. All this, while embracing the best coding has to offer, such as a sound functional paradigm.

Conclusion

Redux has a simple solution to the complex problem of state management. It rests on a functional paradigm to reduce unpredictability. Because reducers are pure functions, it’s super easy to unit test. I decided to use Jest, but any test framework that supports basic assertions will work too.

TypeScript adds an extra layer of protection with type theory. Couple type checking with functional programming and you get sound code that hardly breaks. Best of all, TypeScript stays out of the way while adding value. If you notice, there’s little extra coding once type contracts are in place. The type checker does the rest of the work. Like any good tool, TypeScript automates coding discipline while remaining invisible. TypeScript comes with a loud bark yet gentle bite.

If you wanted to have a play around with this project (and I hope you do), you can find the source code for this article on GitHub.

React-Redux with TypeScript

React-Redux with TypeScript

TypeScript is a typed superset of JavaScript. It has become popular recently in applications due to the benefits it can bring. If you are new to TypeScript it is highly recommended to become familiar with it first before proceeding.

TypeScript is a typed superset of JavaScript. It has become popular recently in applications due to the benefits it can bring. If you are new to TypeScript it is highly recommended to become familiar with it first before proceeding.

TypeScript is a great language to choose if you are a JavaScript developer and interested in moving towards a statically typed language. Using TypeScript is such a logical move for developers that are comfortable with JavaScript but haven’t written in languages that are statically typed (like C, JVM’s, Go, etc).

As I began my journey to TypeScript, (I’m most comfortable with JS, but have written a little bit in Go and C), I found it to be pretty easy to pick up. My initial thought was: “It really isn’t that bad typing all the argument in my function and typing the return value; what’s the fuss all about?” It was nice and simple until we had a project where we needed to create a React/Redux app in TypeScript.

It’s super easy to find material for React + JS, but as you begin to search for React + TS and especially React + Redux + TS, the amount of online tutorials (including YouTube videos) begin to dwindle significantly. I found myself scouring Medium, Stack Overflow, etc. for anything I could find to help explain how to set up the project, how types are flowing between files (especially once Redux is involved), and how to build with Webpack. This article is a way for me to solidify my knowledge of React + Redux + TS, and to hopefully provide some guidance for anyone else who is interested in using this tech stack for the front end. TypeScript is becoming more popular, so I hope this is useful to others in the community.

Prerequisites: I assume you’re aware of how React, Redux, and Webpack work, and also most concepts in TypeScript (at least interfaces and generics).

What are we gonna build? Just to keep it simple, we’ll build the infamous to-do list application. Remember that the purpose is to understand how to set up the project and know how TypeScript integrates with React and Redux. The features that this application will support are:

  1. Add a new item to a list.
  2. Remove an item from the list.

The code for the project can be found here: https://github.com/sterlingdeng/react-redux-ts-boilerplate.

For my project, I didn’t use create-react-app --typescript to get the project started. I found that it was a valuable learning experience to get it started from scratch. I’ll go step by step through the import files and folders needed to get this project up and running. Before we start, let me show you what the final structure looks like.

TS-Redux-React-Boilerplate
├── build
├── node_modules
├── public
│   ├── bundle.js
│   └── index.html
├── src
│   ├── App.tsx
│   ├── index.tsx
│   ├── actions
│   │   ├── actions.ts
│   │   └── index.ts
│   ├── components
│   │   ├── index.ts
│   │   └── TodoItem.tsx
│   ├── containers
│   │   └── TodoContainer.tsx
│   ├── reducers
│   │   ├── index.ts
│   │   └── todoReducers.ts
│   ├── store
│   │   └── store.ts
│   └── types
│       └── types.d.ts
├── .gitignore
├── package-lock.json
├── package.json
├── tslint.json
├── tsconfig.json
├── webpack.config.js
└── README.md

First, let’s look at the package.json file and install these dependencies using npm i.

"dependencies": {
    "@types/node": "^12.0.0",
    "@types/react": "^16.8.15",
    "@types/react-dom": "^16.8.4",
    "@types/react-redux": "^7.0.8",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-redux": "^7.0.3",
    "redux": "^4.0.1",
    "ts-loader": "^5.4.5",
    "typesafe-actions": "^4.2.0",
    "typescript": "^3.4.5",
    "webpack": "^4.30.0",
    "webpack-cli": "^3.3.1"
  }

Let’s first look at the dependencies with the format @types/[npm module here]. If you aren’t familiar with what these modules are, look up https://github.com/DefinitelyTyped/DefinitelyTyped. Since most modules are written in JavaScript, they aren’t written with proper type definitions. Once you attempt to import a module without any type information into a project that is all typed, TypeScript will complain. To prevent this, the community of contributors at DefinitelyTyped create high-quality type definition of the most commonly used JavaScript modules so that those modules will integrate as seamlessly as possible with TS.

You are probably familiar with the next four. ts-loader is needed because Webpack needs a plugin to parse .ts and .tsx files. (This is similar to babel.)

typesafe-actions is a library I use with Redux + TypeScript. Without it, the files can get quite noisy in terms of declaring types for the Store, Reducer, and Actions. This library provides methods that infer type definition for redux code so that the files are a bit cleaner and focused.

webpack and webpack-cli are used to bundle the .ts and .tsx files into one.js file that can be sent to the front end.

Next, let’s look at thetsconfig.json file. The purpose of this file is to configure how you want the ts compiler to run.

{
  "compilerOptions": {
    "baseUrl": ".",
    "outDir": "build/dist",
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react"
  }
}

baseUrl denotes the folder. outDir directs the compiler where it should put the compiled code. module tells the compiler which JavaScript module types to use. target tells the compiler which JS version to target. sourceMap tells the compiler to create a bundle.js.map along with bundle.js. Because bundling will turn multiple files into one large .js file, troubleshooting code will be difficult because you wouldn’t easily know which file and at which line the code failed (since everything is just one big file). The .map file will map the bundled file to the respective unbundled file.

tslint.json provides options on how strict or loose you want the ts linter to be. The various options you can set for the linter can be found online.

Action Creators

Normally when I start projects with Redux, I begin at the action creators. Let’s quickly review the features that we need to implement: Adding an item to a list and removing an item from the list. This means we’ll need two action creators, one for adding and another for removing.

import { action } from "typesafe-actions";

// use typescript enum rather than action constants
export enum actionTypes {
  ADD = "ADD",
  DELETE = "DELETE"
}

export const todoActions = {
  add: (item: string) => action(actionTypes.ADD, item),
  delete: (idx: number) => action(actionTypes.DELETE, idx)
};

In the actions.ts file, I’m using the enum feature in TS to create the action constants. Secondly, I’m using the action method provided from the typesafe-actions module. The first argument you pass into the method is a string which represents that action, and the second argument is the payload. The add method will add an item to the list of to-dos, and the deletemethod will remove an item, based on the provided index, from the list of to-dos.

In terms of type safety, what we want in our reducers file is the proper type of the payload, given a specific action. The feature in TypeScript that provides this support is called discriminated union and type guarding. Consider the example below:

// this is an example of discriminated unions
// this file isn't used in the project

interface ActionAdd {
  type: "ADD",
  payload: string
}

interface ActionDelete {
  type: "DELETE",
  payload: number
}

type Actions = ActionAdd | ActionDelete

function reducer(a: Actions) {
  switch(a.type) {
    case "ADD" : {
      // payload is a string
    }
    case "DELETE" : {
      // payload is a number
    }
  }
}

Given the shape of the two action objects, we can discriminate between them based on the type property. Using control flow analysis, like if-else or switch-case statements, it’s very logical that in line 16, the only type that the payload can be is a string. Since we only have two actions, the remaining payload in line 22 will be a number. If you are interested in learning more about discriminated unions and type guarding, I would recommend learning more about it here and here.

Reducer

After defining our action creators, let’s create the reducer for this project.

import * as MyTypes from "MyTypes";
import { actionTypes } from "../actions/";

interface ITodoModel {
  count: number;
  list: string[];
}

export const initialState: ITodoModel = {
  count: 2,
  list: ["Do the laundry", "Do the dishes"]
};

export const todoReducer = (state: ITodoModel = initialState, action: MyTypes.RootAction) => {
  switch (action.type) {
    case actionTypes.ADD: {
      return {
        ...state,
        count: state.count + 1,
        list: [...state.list, action.payload]
      };
    }
    case actionTypes.DELETE: {
      const oldList = [...state.list];
      oldList.splice(action.payload, 1);
      const newList = oldList;

      return {
        ...state,
        count: state.count - 1,
        list: newList
      };
    }
    default:
      return state;
  }
};

In lines four through seven, I’m defining the model (or schema) of our Todostore. It will keep track of how many to-do items we have, as well as the array of strings. Lines nine through 12 are the initial state when the application first starts. Within the todoReducer function, we want type safety within the casestatements. Based on the earlier gist, we accomplished that by discriminated unions and type guarding, done by typing the action parameter. We have to first define an interface for every action object, and then create a union of them all and assign that to a type. This can get tedious if we have a lot of action creators — luckily, typesafe-actions has methods to help create the proper typing of the action creators without having to actually write out all the interfaces.

declare module "MyTypes" {
  import { StateType, ActionType } from "typesafe-actions";
  // 1 for reducer, 1 for action creators
  export type ReducerState = StateType<typeof import("../reducers").default>;
  export type RootAction = ActionType<typeof import("../actions/actions")>;
}

Ignoring line four for now and focusing on line five, we use a method called ActionType from the module, and import the actions from actions.ts to create the discriminated union types, which are then assigned to a type called RootAction. In line one of the todoReducers.ts, we import MyTypes and in line 14, we type the action parameter with MyTypes.RootAction. This allows us to have IntelliSense and autocompletion within the reducers!

Now that we have the reducer set up, the ReducerState type from the types.d.ts file allows TypeScript to infer the shape of the state object in the reducer function. This will provide IntelliSense when we try to access the payload object within the Reducer. An example of what that looks like is in the picture below.

IntelliSense in the Reducer

Redux Store

Finally, let’s hook up the reducer to the redux store.

import { createStore } from "redux";
import rootReducer from "../reducers";

const store = createStore(rootReducer);

export default store;

Let’s recap what we have accomplished up until this point. We have created and typed our action creators using the action method from typesafe-actions. We have created our types.d.ts file which provide type information on our action creators and reducer state. The reducer has been created and the actions are typed by using MyTypes.RootAction, which provide invaluable auto-completion information of the payload within the reducer’s case statements. And lastly, we created our Redux store.

React and TS

Let’s change gears and begin working on creating and typing our React components. I’ll go over examples of how to properly type both function and class based components, along with instructions on how to type both the props and state (for stateful components).

App.tsx

import * as React from "react";
import TodoContainer from "./containers/TodoContainer";

export const App: React.FC<{}> = () => {
  return (
    <>
      <h1>React Redux Typescript</h1>
      <TodoContainer />
    </>
  );
};

App is a functional component that is typed by writing const App: React.FC<{}>. (FC refers to functional component.) If you aren’t familiar with generics (which is the <{}> ), I think of them like variables but for types. Since the shape of props and state can differ based on different use cases, generics are a way for us to, well, make the component generic! In this case, App doesn’t take any props; therefore, we pass in an empty object as the generic. How do we know that the generic is specifically for props? If you use VS code, IntelliSense will let you know what type it needs.

Where it says <P = {}> , it means type {} has been assigned to P, where Pstands for props. For class-based components, React will use S to refer to state. App is a functional component that receives no props and is not connected to the Redux store. Let’s go for something a little more complicated.

TodoContainer.tsx

import * as React from "react";
import { connect } from "react-redux";
import { Dispatch } from "redux";
import * as MyTypes from "MyTypes";
import { actionTypes } from "../actions";
import { TodoItem } from "../components";

interface TodoContainerState {
  todoInput: string;
}

interface TodoContainerProps {
  count: number;
  todoList: string[];
  addToDo: (item: string) => object;
  deleteToDo: (idx: number) => object;
}

class TodoContainer extends React.Component<TodoContainerProps, TodoContainerState> {
  constructor(props) {
    super(props);
    this.state = {
      todoInput: ""
    };
  }

  handleTextChange = e => {
    this.setState({
      todoInput: e.target.value
    });
  };

  handleButtonClick = () => {
    this.props.addToDo(this.state.todoInput);
    this.setState({
      todoInput: ""
    });
  };

  handleDeleteButtonClick = (idx: number) => {
    console.log("deleting", idx);
    this.props.deleteToDo(idx);
  };

  render() {
    let todoJSX: JSX.Element[] | JSX.Element;
    if (!this.props.todoList.length) {
      todoJSX = <p>No to do</p>;
    } else {
      todoJSX = this.props.todoList.map((item, idx) => {
        return (
          <TodoItem item={item} key={idx} idx={idx} handleDelete={this.handleDeleteButtonClick} />
        );
      });
    }

    return (
      <div>
        {todoJSX}
        <input
          onChange={this.handleTextChange}
          placeholder={"New To Do Here"}
          value={this.state.todoInput}
        />
        <button onClick={this.handleButtonClick}>Add To Do</button>
      </div>
    );
  }
}

const MapStateToProps = (store: MyTypes.ReducerState) => {
  return {
    count: store.todo.count,
    todoList: store.todo.list
  };
};

const MapDispatchToProps = (dispatch: Dispatch<MyTypes.RootAction>) => ({
  addToDo: (item: string) => dispatch({ type: actionTypes.ADD, payload: item }),
  deleteToDo: (idx: number) => dispatch({ type: actionTypes.DELETE, payload: idx })
});

export default connect(
  MapStateToProps,
  MapDispatchToProps
)(TodoContainer);

OK, TodoContainer.tsx is the most complicated of them all, but I’ll walk you through what’s going on in the code. TodoContainer is a React Class Component because I need it to hold in its state the value for the input box. It is also connected to the redux store, so it’ll have MapStateToProps and MapDispatchToProps . First, I’ve definedTodoContainerState . Since I’ll be holding the value of the input box in state, I’ll type the property as a string.

Next, I’ve defined TodoContainerProps, which will be the shape of the Container’s props.

Because class-based components can have both state and props, we should expect that there should be at least two generics that we need to pass into React.Component.

P for Props and S for State

If you mouse over React.Component, you can see that it takes in three generics, P, S, and SS. The first two generics are props and state. I’m not quite sure whatSS is and what the use case is. If anyone knows, please let me know in the comments below.

After passing in the generics into React.Component , IntelliSense and autocompletion will work within this.state and for props.

Next, we want to type MapStateToProps and MapDispatchToProps. This is easily achievable by leveraging the MyTypes module that we built in the redux section. For MapStateToProps, we assign the store type to be MyTypes.ReducerState. An example of the IntelliSense it will provide is in the below screenshot.

IntelliSense for MapStateToProps

Lastly, we want to have type safety within MapDispatchToProps. The benefit that is provided is a type-safe payload given an action type.

Type-safe payloads

In the screenshot above, I purposely typed item as a boolean. Immediately, the TSServer will pick up that the boolean payload within MapDispatchToProps is not correct because it’s expecting the payload to be a string, given that the type is actionTypes.ADD. TodoContainer.tsx has the most going on since it is a class based React component, with both state and props, and is also connected to the store.

Before we wrap up, let’s look at our last component: TodoItem.tsx

TodoItem.tsx

This component is a functional component with props — code below.

import * as React from "react";

interface TodoItemProps {
  item: string;
  idx: number;
  handleDelete: (idx: number) => void;
}

export const TodoItem: React.FC<TodoItemProps> = props => {
  return (
    <span>
      {props.item}
      <button onClick={() => props.handleDelete(props.idx)}>X</button>
    </span>
  );
};

The shape of the props are defined in the interface TodoItemProps. The type information is passed into as a generic in React.FC. Doing so will provide auto-completion for props within the component. Awesome.

Another great feature that TypeScript provides when used with React is IntelliSense for props when rendering React Components within JSX. As an example, if you delete idx:number from TodoItemProps and then you navigate to TodoContainer.tsx, an error will appear at the place where you render <TodoItem />.

Property ‘idx’ does not exist

Because we removed idx from the TodoItemProps interface, TypeScript is letting us know that we have provided an additional prop that it couldn’t find, idx, into the component.

Lastly, let’s build the project using Webpack. In the command line, type npm run build. In the public folder within the root directory, you should see bundle.js alongsideindex.html. Open index.html in any browser and you should see a very simple, unstyled, to-do app.

After webpack build

I hope that I was able to demonstrate the power of TypeScript coupled with React and Redux. It may seem a bit overkill for our simple to-do list app — you just need to imagine the benefit of TS + React + Redux at scale. It will help new developers read the code quicker, provide more confidence in refactoring, and ultimately improve development speed.

If you need more reference and material, I used the following two Git repos to teach myself

Both these repos have proved invaluable for my learning, and I hope they will be the same for you.

Understanding React with Redux and Redux Thunk for Beginners

Understanding React with Redux and Redux Thunk for Beginners

Introduction

Redux, according to the offical docs, is a predictable state container for JavaScript apps written by Dan Abramov. It’s a lightweight implementation of Flux, which is another library for managing the state. Basically Redux took the ideas that Flux brought in, leaving out its complexity by “borrowing” things from Elm.

For starters, there are several key concepts to understand: store, actions / action creators, and reducers. The official documentation is pretty straightforward and also plenty of examples and nice analogies can be found on the internet.

Principles

Redux has three fundamental principles:

  • single source of truth

The whole state of the application is stored in an object tree (within a single store). Visualize the state as a “model”, but without setters. As a plus, a single state tree enables us to debug our application with ease.

  • state is read-only

In order to modify state in Redux, actions have to be dispatched. Actions are a plain JavaScript object that describe what changed, sending data from the application to the store.

An action will look like this:

{
      type: 'ACTION_TYPE',
      action_value: string
  }

  • changes are made with pure functions

In order to tie state and actions together, we write a function called a reducer that takes two parameters: the (soon to be previous) state and an action. This pure function applies the action to that state and returns the desired next state.

Example of a reducer:

 export function reducer(state = '', action) {
      switch (action.type) {
          case 'ACTION_TYPE':
              return action.action_value;
          default:
              return state;
      }
  } 

Important: Reducers do not store state, and they do not mutate state. You pass state to the reducer and the reducer will return state.

Tip: As a best practice, even though it’s possible to have a single reducer that manages the transformation done by every action, it is better to use reducer composition - breaking down the reducer into multiple, smaller reducers, each of them handling a specific slice of the application state.

How it works

When one action is dispatched to the store, the combined reducer catches the action and sends it to each of the smaller reducers. Each smaller reducer examines what action was passed and dictates if and how to modify that part of state. You will find an example of a combined reducer a bit later in the article.

After each smaller reducer produces its corresponding next state, an updated state object will be saved in the store. Because this is important, I’m mentioning again that the store is the single source of truth in our application. Therefore, when each action is run through the reducers, a new state is produced and saved in the store.

Besides all of this, Redux comes up with another concept, action creators, which are functions that return actions. These can be linked to React components and when interacting with your application, the action creators are invoked (for example in one of the lifecycle methods) and create new actions that get dispatched to the store.

 export function actionCreator(bool) {
        return {
            type: 'ACTION_TYPE',
            action_value: bool
        };
    }

Fetching data from an API

Now onto our application. All of the above code snippets were just examples. We will now dive into the important bits of the code of our app. Also, a github repo will be available at the end of the article, containing the entire app.

Our app will fetch (asynchronously) data that is retrieved by an API - assuming we already built and deployed a working API, how convenient :) - and then display the fetched data as nice as my UI design skills go (not too far).

TVmaze’s public API contains tonnes of data and we will fetch all the shows they have ever aired. Then, the app will display all the shows, toghether with their rating and premiere date.

Designing our state

In order for this application to work properly, our state needs to have 3 properties: isLoading, hasError and items. So we will have one action creator for each property and an extra action creator where we will fetch the data and call the other 3 action creators based on the status of our request to the API.

Action creators

Let’s have a look at the first 3 action creators

export function itemsHaveError(bool) {
        return {
            type: 'ITEMS_HAVE_ERROR',
            hasError: bool
        };
    }

    export function itemsAreLoading(bool) {
        return {
            type: 'ITEMS_ARE_LOADING',
            isLoading: bool
        };
    }

    export function itemsFetchDataSuccess(items) {
        return {
            type: 'ITEMS_FETCH_DATA_SUCCESS',
            items
        };
    }

The first 2 action creators will receive a bool as a parameter and they will return an object with that bool value and the corresponding type.

The last one will be called after the fetching was successful and will receive the fetched items as an parameter. This action creator will return an object with a property called items that will receive as value the array of items which were passed as an argument. Instead if items: items, we can just write items, using an ES6 syntactic sugar called property shorthand.

To visualize a bit what was described earlier, this is how it looks in Redux DevTools:

This is image title

Out of the box, action creators can return just actions. That’s where Redux Thunk comes in handy. Thunk allows us to have action creators that return a function instead of an action and dispatch an action only in certain cases.

If it wasn’t for Redux Thunk, we would probably end up having just one action creator, something like this:

export function itemsFetchData(url) {
        const items = axios.get(url);

        return {
            type: 'ITEMS_FETCH_DATA',
            items
        };
    }

Obviously, it would be a lot harder in this scenario to know if the items are still loading or checking if we have an error.

Knowing these and using Redux Thunk, our action creator will be:

 export function itemsFetchData(url) {
        return (dispatch) => {
            dispatch(itemsAreLoading(true));

            axios.get(url)
                .then((response) => {
                    if (response.status !== 200) {
                        throw Error(response.statusText);
                    }

                    dispatch(itemsAreLoading(false));

                    return response;
                })
                .then((response) => dispatch(itemsFetchDataSuccess(response.data)))
                .catch(() => dispatch(itemsHaveError(true)));
        };
    }

Reducers

Now that we have our action creators in place, let’s start writing our reducers.

All reducers will be called when an action is dispatched. Because of this, we are returning the original state in each of our reducers. When the action type matches, the reducer does what it has to do and returns a new slice of state. If not, the reducer returns the original state back.

Each reducer takes 2 parameters: the (soon to be previous) slice of state and an action object:

export function itemsHaveError(state = false, action) {
        switch (action.type) {
            case 'ITEMS_HAVE_ERROR':
                return action.hasError;
            default:
                return state;
        }
    }

    export function itemsAreLoading(state = false, action) {
        switch (action.type) {
            case 'ITEMS_ARE_LOADING':
                return action.isLoading;
            default:
                return state;
        }
    }

    export function items(state = [], action) {
        switch (action.type) {
            case 'ITEMS_FETCH_DATA_SUCCESS':
                return action.items;
            default:
                return state;
        }
    }

Now that we have the reducers created, let’s combine them in our index.js from our reducers folder:

 import { combineReducers } from 'redux';
    import { items, itemsHaveError, itemsAreLoading } from './items';

    export default combineReducers({
        items,
        itemsHaveError,
        itemsAreLoading
    });

Creating the store

Don’t forget about including the Redux Thunk middleware in the configureStore.js:


 import { createStore, applyMiddleware } from 'redux';
    import thunk from 'redux-thunk';
    import rootReducer from '../reducers';

    export default function configureStore(initialState) {
        const composeEnhancers = 
            window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?   
                window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
                    // options like actionSanitizer, stateSanitizer
                }) : compose;

        const enhancer = composeEnhancers(
            applyMiddleware(thunk)
        );

        return createStore(
            rootReducer,
            initialState,
            enhancer
        );
    }

Using the store in our root index.js

 import React from 'react';
    import { render } from 'react-dom';
    import { Provider } from 'react-redux';
    import configureStore from './store/configureStore';

    import ItemList from './components/ItemList';

    const store = configureStore();

    render(
        <Provider store={store}>
            <ItemList />
        </Provider>,
        document.getElementById('app')
    );

Writing our React component which shows the fetched data

Let’s start by talking about what we are importing here.

In order to work with Redux, we have to import connect from ‘react-redux’:

    import { connect } from 'react-redux';

Also, because we will fetch the data in this component, we will import our action creator that fetches data:

    import { itemsFetchData } from '../actions/items';

We are importing only this action creator, because this one also dispatches the other actions to the store.

Next step would be to map the state to the components’ props. For this, we will write a function that receives state and returns the props object.

const mapStateToProps = (state) => {
        return {
            items: state.items,
            hasError: state.itemsHaveError,
            isLoading: state.itemsAreLoading
        };
    };

When we have a new state, the props in our component will change according to our new state.

Also, we need to dispatch our imported action creator.

    const mapDispatchToProps = (dispatch) => {
        return {
            fetchData: (url) => dispatch(itemsFetchData(url))
        };
    };


With this one, we have access to our itemFetchData action creator through our props object. This way, we can call our action creator by doing this.props.fetchData(url);

Now, in order to make these methods actually do something, when we export our component, we have to pass these methods as arguments to connect. This connects our component to Redux.

    export default connect(mapStateToProps, mapDispatchToProps)(ItemList);

Finally, we will call this action creator in the componentDidMount lifecycle method:

    this.props.fetchData('http://api.tvmaze.com/shows');


Side note: if you are wondering why are we calling the action creator in componentDidMount instead of other lifecycle methods, I have found a couple of good reasons here:

  • You can’t guarantee the AJAX request won’t resolve before the component mounts. If it did, that would mean that you’d be trying to setState on an unmounted component, which not only won’t work, but React will yell at you for. Doing AJAX in componentDidMount will guarantee that there’s a component to update.

  • Fiber, the next implementation of React’s reconciliation algorithm, will have the ability to start and stop rendering as needed for performance benefits. One of the trade-offs of this is that componentWillMount, the other lifecycle event where it might make sense to make an AJAX request, will be “non-deterministic”. What this means is that React may start calling componentWillMount at various times whenever it feels like it needs to. This would obviously be a bad formula for AJAX requests.

Besides this, we need some validations:

    if (this.props.hasError) {
        return <p>Sorry! There was an error loading the items</p>;
    }

    if (this.props.isLoading) {
        return <p>Loading ...</p>;
    }


And the actual iteration over our fetched data array:

 {this.props.items.map((item) => (
        // display data here
    ))}

In the end, our component will look like this:

 import React, { Component, PropTypes } from 'react';
    import { connect } from 'react-redux';
    import { ListGroup, ListGroupItem } from 'react-bootstrap';
    import { itemsFetchData } from '../actions/items';

    class ItemList extends Component {
        componentDidMount() {
            this.props.fetchData('http://api.tvmaze.com/shows');
        }

        render() {
            if (this.props.hasError) {
                return <p>Sorry! There was an error loading the items</p>;
            }

            if (this.props.isLoading) {
                return <p>Loading ...</p>;
            }

            return (
                <div style={setMargin}>
                    {this.props.items.map((item) => (
                        <div key={item.id}>
                                <ListGroup style={setDistanceBetweenItems}>
                                    <ListGroupItem href={item.officialSite} header={item.name}>
                                        Rating: {item.rating.average}
                                        <span className="pull-xs-right">Premiered: {item.premiered}</span>
                                    </ListGroupItem>
                                </ListGroup>
                        </div>
                    ))}
                </div>
            );
        }
    }

    ItemList.propTypes = {
        fetchData: PropTypes.func.isRequired,
        items: PropTypes.array.isRequired,
        hasError: PropTypes.bool.isRequired,
        isLoading: PropTypes.bool.isRequired
    };

    const mapStateToProps = (state) => {
        return {
            items: state.items,
            hasError: state.itemsHaveError,
            isLoading: state.itemsAreLoading
        };
    };

    const mapDispatchToProps = (dispatch) => {
        return {
            fetchData: (url) => dispatch(itemsFetchData(url))
        };
    };

    export default connect(mapStateToProps, mapDispatchToProps)(ItemList);

And that was all !

Our app will look like this:
This is image title

I wasn’t lying about my design skills, was I ? :)

Last words and other resources

We now have an app that is fetching data asynchronously from an API, using React for our UI and Redux for managing the state of our application. I think this is a good starting point for a personal / small project and also you get to work with new technologies.

This doesn’t mean that Redux is the solution for every problem we face when writing apps in React or that Redux is a a must-use in any Javascript written project, as Dan Abramov states in an interesting article.

Also worth noting, Facebook are preparing React Fiber, a reimplementation of React. They state that its goal is to make it more suitable for animations and gestures and that the key new feature will be incremental rendering which is:

  • the ability to split rendering work into chunks and spread it out over multiple frames

Redux and mat-selection-list in Angular

Redux and mat-selection-list in Angular

In this post, we look at a couple pieces of code that can help Angular developers better understand the framework and working with TypeScript.

In this post, we look at a couple pieces of code that can help Angular developers better understand the framework and working with TypeScript.

How to Install Redux Dev Tools in Angular 6
  1. Install Redux Dev Tools from the Chrom web store.
  2. Install ngrx dev tools in your Angular project:
npm install @ngrx/[email protected] --save

3. Add the ngrx dev tools module to your project:

import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from '../environments/environment'; // Angular CLI environemnt

@NgModule({
  imports: [
    StoreModule.forRoot(reducers),
    // Instrumentation must be imported after importing StoreModule (config is optional)
    StoreDevtoolsModule.instrument({
      maxAge: 25, // Retains last 25 states
      logOnly: environment.production, // Restrict extension to log-only mode
    }),
  ],
})
export class AppModule {}

mat-selection-list for select all checkbox in Angular 6

HTML with inline tutorial:

 <mat-selection-list formControlName="areasCtrl" role="list">
   <!-- add select all option here and add select all event -->
      <mat-list-option #areaSelectAll value="ALL" (click)="areaSelectAllEvent()" aria-label="select all">Select All</mat-list-option>
      <mat-list-option *ngFor="let area of areaArray" [value]="area.areaName" aria-label="{{area.areaFullName}}">
        {{area.areaFullName}}
      </mat-list-option>
 </mat-selection-list>

Component part (TypeScript code with tutorial notes given in the comments):

/*
select all event for select all option

areaSelectAllEvent is used to reset areasCtrl formcontrol with all the list of value
or with empty list of value

*/
areaSelectAllEvent(){
    if(this.areaSelectAll.selected){
      let allList = this.getAreaValueFromList(this.areaArray);
         allList.unshift('ALL');
      console.log(allList);
      this.spForm.get('areasCtrl').setValue(allList, {emitEvent: false});
      this.selAreas = allList; 
  }else{
      this.spForm.get('areasCtrl').setValue([]);
  }
 }

/*
value changes for area form contontrol

*/
this.spForm.get('areasCtrl').valueChanges.subscribe(areas =>{

      //add feature for select all if selecte all is set, check other option will reset the select all
      let area = areas;
      if(area.includes('ALL') && area.length > 1  && area.length < this.areaArray.length+1){        

        const dif = _.difference(area,this.selAreas); //compare current value with previous value
          if(dif[0] !== 'ALL'){
            area.shift(); // remvoe all from array
            this.spForm.get('areasCtrl').setValue(area);
          }         
      }

      this.selAreas=areas;
    })

How to Implement Redux in 24 Lines of JavaScript?

How to Implement Redux in 24 Lines of JavaScript?

Redux is among the most important JavaScript libraries ever created. In this posr, you'll learn how to Implement Redux in 24 lines of JavaScript. Inspired by prior art like [Flux](https://facebook.github.io/flux/) and...

Redux is among the most important JavaScript libraries ever created. In this posr, you'll learn how to Implement Redux in 24 lines of JavaScript.

Inspired by prior art like Flux and Elm, Redux put JavaScript functional programming on the map by introducing a scalable architecture of three simple points.

If you're new to Redux, consider reading the official docs first.

Redux Is Mostly Convention

Consider this simple counter application that uses the Redux architecture. If you'd like to jump ahead check out the Github repo for it.

redux-counter-app-demo

State lives in a single tree

The application's state looks like this.

const initialState = { count: 0 };

Actions declare state changes

By Redux convention, I do not directly modify (mutate) the state.

// DON'T do this in a Redux app
state.count = 1;

Instead I create all the actions the user may leverage in the application.

const actions = {
  increment: { type: 'INCREMENT' },
  decrement: { type: 'DECREMENT' }
};

Reducer interprets action and updates state

The last architectural piece calls for a reducer, a pure function that returns a new copy of your state based on the previous state and action.

  • If increment is fired, increment state.count.
  • If decrement is fired, decrement state.count.
const countReducer = (state = initialState, action) => {
  switch (action.type) {
    case actions.increment.type:
      return {
        count: state.count + 1
      };

    case actions.decrement.type:
      return {
        count: state.count - 1
      };

    default:
      return state;
  }
};

No Redux so far

Did you notice that we haven't touched the Redux library yet? We've just created some objects and a function. This is what I mean by "mostly convention", 90% of Redux doesn't require Redux!

Let's implement Redux

To put this architecture to use, we must plug it into a store. We'll implement just one function–createStore.

It's used like this.

import { createStore } from 'redux'

const store = createStore(countReducer);

store.subscribe(() => {
  console.log(store.getState());
});

store.dispatch(actions.increment);
// logs { count: 1 }

store.dispatch(actions.increment);
// logs { count: 2 }

store.dispatch(actions.decrement);
// logs { count: 1 }

And here's our initial boilerplate. We'll need a list of listeners and the initial state supplied by the reducer.

const createStore = (yourReducer) => {
    const listeners = [];
    let currentState = yourReducer(undefined, {});
}

Whenever someone subscribes to our store, they get added to the listeners array. The is important because every time someone dispatches an action, all the listeners must be notified in a loop.

Calling yourReducer with undefined and an empty object returns the initialState we installed up above. This gives us a proper value to return when we call store.getState(). Speaking of which, let's create that method.

store.getState()

This is a function that returns the latest state from the store. We'll need this to update our UI every time the user clicks a button.

const createStore = (yourReducer) => {
    const listeners = [];
    let currentState = yourReducer(undefined, {});

    return {
        getState: () => currentState
    };
}

store.dispatch(action)

This is a function that takes an action as a parameter. It feeds that action and the currentState to yourReducer to get a new state. Then dispatch notifies everyone subscribed to the store.

const createStore = (yourReducer) => {
  const listeners = [];
  let currentState = yourReducer(undefined, {});

  return {
    getState: () => currentState,
    dispatch: (action) => {
      currentState = reducer(currentState, action);

      listeners.forEach((listener) => {
        listener();
      });
    }
  };
};

store.subscribe(listener)

This is a function that lets you be notified when the store receives an action It's good to use store.getState() in here to get your latest state and update your UI.

const createStore = (yourReducer) => {
  const listeners = [];
  let currentState = yourReducer(undefined, {});

  return {
    getState: () => currentState,
    dispatch: (action) => {
      currentState = reducer(currentState, action);

      listeners.forEach((listener) => {
        listener();
      });
    },
    subscribe: (newListener) => {
      listeners.push(newListener);

      const unsubscribe = () => {
        listeners = listeners.filter((l) => l === newListener);
      };

      return unsubscribe;
    }
  };
};

subscribe returns a function called unsubscribe that you can call when you're no longer interested in listening to the store's updates.

All Together Now

Let's hook this up to our buttons and view the final source code.

// simplified createStore function
const createStore = (reducer) => {
  const listeners = [];
  let currentState = reducer(undefined, {});

  return {
    getState: () => currentState,
    dispatch: (action) => {
      currentState = reducer(currentState, action);

      listeners.forEach((listener) => {
        listener();
      });
    },
    subscribe: (newListener) => {
      listeners.push(newListener);

      const unsubscribe = () => {
        listeners = listeners.filter((l) => l === newListener);
      };

      return unsubscribe;
    }
  };
};

// Redux architecture pieces
const initialState = { count: 0 };

const actions = {
  increment: { type: 'INCREMENT' },
  decrement: { type: 'DECREMENT' }
};

const countReducer = (state = initialState, action) => {
  switch (action.type) {
    case actions.increment.type:
      return {
        count: state.count + 1
      };

    case actions.decrement.type:
      return {
        count: state.count - 1
      };

    default:
      return state;
  }
};

const store = createStore(countReducer);

// DOM elements
const incrementButton = document.querySelector('.increment');
const decrementButton = document.querySelector('.decrement');

// Wire click events to actions
incrementButton.addEventListener('click', () => {
  store.dispatch(actions.increment);
});

decrementButton.addEventListener('click', () => {
  store.dispatch(actions.decrement);
});

// Initialize UI display
const counterDisplay = document.querySelector('h1');
counterDisplay.innerHTML = parseInt(initialState.count);

// Update UI when an action fires
store.subscribe(() => {
  const state = store.getState();

  counterDisplay.innerHTML = parseInt(state.count);
});

And once again here's our final UI.

redux-counter-app-demo

If you're interested in the HTML/CSS I used, here's the GitHub repo again!

Thanks for reading

Best 50 React Interview Questions for Frontend Developers in 2019

Best 50 React Interview Questions for Frontend Developers in 2019

In this article, you'll see best React interview questions which an aspiring front end developer must prepare in 2019 for React interviews.

In this article, you'll see best React interview questions which an aspiring front end developer must prepare in 2019 for React interviews.

So, here are the Top 50 React Interview Questions and Answers which are most likely to be asked by the interviewer. For your ease of access, I have categorized the React interview questions namely:
General React Interview QuestionsReact Component Interview QuestionsReact Redux Interview QuestionsReact Router Interview Questions#

General React – React Interview Questions 1. Differentiate between Real DOM and Virtual DOM.

2. What is React?

React is a front-end JavaScript library developed by Facebook in 2011.It follows the component based approach which helps in building reusable UI components.It is used for developing complex and interactive web and mobile UI.Even though it was open-sourced only in 2015, it has one of the largest communities supporting it.## **3. What are the features of React? **

Major features of React are listed below:
It uses the virtual DOM instead of the real DOM.It uses server-side rendering.It follows uni-directional data flow or data binding.## 4. List some of the major advantages of React.

Some of the major advantages of React are:
It increases the application’s performanceIt can be conveniently used on the client as well as server sideBecause of JSX, code’s readability increasesReact is easy to integrate with other frameworks like Meteor, Angular, etcUsing React, writing UI test cases become extremely easy## 5. What are the limitations of React?

Limitations of React are listed below:
React is just a library, not a full-blown frameworkIts library is very large and takes time to understandIt can be little difficult for the novice programmers to understandCoding gets complex as it uses inline templating and JSX## 6. What is JSX?

JSX is a shorthand for JavaScript XML. This is a type of file used by React which utilizes the expressiveness of JavaScript along with HTML like template syntax. This makes the HTML file really easy to understand. This file makes applications robust and boosts its performance. Below is an example of JSX:

render(){
    return(       
          
 
 

             
 
 
# Hello World from Edureka!!

 
 
 
         
 
 
 
    );
}

7. What do you understand by Virtual DOM? Explain its working.

A virtual DOM is a lightweight JavaScript object which originally is just the copy of the real DOM. It is a node tree that lists the elements, their attributes and content as Objects and their properties. React’s render function creates a node tree out of the React components. It then updates this tree in response to the mutations in the data model which is caused by various actions done by the user or by the system.

This Virtual DOM works in three simple steps.
Whenever any underlying data changes, the entire UI is re-rendered in Virtual DOM representation.

Then the difference between the previous DOM representation and the new one is calculated.

Once the calculations are done, the real DOM will be updated with only the things that have actually changed. ## 8. Why can’t browsers read JSX?

Browsers can only read JavaScript objects but JSX in not a regular JavaScript object. Thus to enable a browser to read JSX, first, we need to transform JSX file into a JavaScript object using JSX transformers like Babel and then pass it to the browser.

9. How different is React’s ES6 syntax when compared to ES5?

Syntax has changed from ES5 to ES6 in following aspects:
require vs import

// ES5
var React = require('react');
 
// ES6
import React from 'react';

  • export vs exports
// ES5
module.exports = Component;
 
// ES6
export default Component;

  • component and function
// ES5
var MyComponent = React.createClass({
    render: function() {
        return
 
 
### Hello Edureka!

 
 
 
;
    }
});
 
// ES6
class MyComponent extends React.Component {
    render() {
        return
 
 
### Hello Edureka!

 
 
 
;
    }
}

  • props
// ES5
var App = React.createClass({
    propTypes: { name: React.PropTypes.string },
    render: function() {
        return
 
 
### Hello, {this.props.name}!

 
 
 
;
    }
});
 
// ES6
class App extends React.Component {
    render() {
        return
 
 
### Hello, {this.props.name}!

 
 
 
;
    }
}

  • state
// ES5
var App = React.createClass({
    getInitialState: function() {
        return { name: 'world' };
    },
    render: function() {
        return
 
 
### Hello, {this.state.name}!

 
 
 
;
    }
});
 
// ES6
class App extends React.Component {
    constructor() {
        super();
        this.state = { name: 'world' };
    }
    render() {
        return
 
 
### Hello, {this.state.name}!

 
 
 
;
    }
}

10. How is React different from Angular? **React **Components – React Interview Questions 11. What do you understand from “In React, everything is a component.”

Components are the building blocks of a React application’s UI. These components split up the entire UI into small independent and reusable pieces. Then it renders each of these components independent of each other without affecting the rest of the UI.

12. Explain the purpose of render() in React.

Each React component must have a **render() **mandatorily. It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag such as , , etc. This function must be kept pure i.e., it must return the same result each time it is invoked.

13. How can you embed two or more components into one?

We can embed components into one in the following way:

class MyComponent extends React.Component{
    render(){
        return(         
             
 
 

               
                 
 
 
# Hello

 
 
 
                
            
 
 
 
        );
    }
}
class Header extends React.Component{
    render(){
        return
 
 
# Header Component

 
 
 
    
   };
}
ReactDOM.render(
    , document.getElementById('content')
);

14. What is Props?

Props is the shorthand for Properties in React. They are read-only components which must be kept pure i.e. immutable. They are always passed down from the parent to the child components throughout the application. A child component can never send a prop back to the parent component. This help in maintaining the unidirectional data flow and are generally used to render the dynamically generated data.

15. What is a state in React and how is it used?

States are the heart of React components. States are the source of data and must be kept as simple as possible. Basically, states are the objects which determine components rendering and behavior. They are mutable unlike the props and create dynamic and interactive components. They are accessed via this.state().

16. Differentiate between states and props.

17. How can you update the state of a component?

State of a component can be updated using this.setState().

class MyComponent extends React.Component {
    constructor() {
        super();
        this.state = {
            name: 'Maxx',
            id: '101'
        }
    }
    render()
        {
            setTimeout(()=>{this.setState({name:'Jaeha', id:'222'})},2000)
            return (             
                    
 
 

                   
                      
 
 
# Hello {this.state.name}

 
 
 
                 
                      
 
 
## Your Id is {this.state.id}

 
 
 
                   
 
 
 
            );
        }
    }
ReactDOM.render(
    , document.getElementById('content')
);

18. What is arrow function in React? How is it used?

Arrow functions are more of brief syntax for writing the function expression. They are also called ‘fat arrow‘ (=>) the functions. These functions allow to bind the context of the components properly since in ES6 auto binding is not available by default. Arrow functions are mostly useful while working with the higher order functions.

//General way
render() {   
    return(
        
    );
}
//With Arrow Function
render() { 
    return(
         this.handleOnChange(e) } />
    );
}

19. Differentiate between stateful and stateless components.

20. What are the different phases of React component’s lifecycle?

There are three different phases of React component’s lifecycle:
Initial Rendering Phase: This is the phase when the component is about to start its life journey and make its way to the DOM.*Updating Phase: *Once the component gets added to the DOM, it can potentially update and re-render only when a prop or state change occurs. That happens only in this phase.*Unmounting Phase: *This is the final phase of a component’s life cycle in which the component is destroyed and removed from the DOM.## 21. Explain the lifecycle methods of React components in detail.

Some of the most important lifecycle methods are:
componentWillMount() **Executed just before rendering takes place both on the client as well as server-side.componentDidMount() **Executed on the client side only after the first render.***componentWillReceiveProps() ***– Invoked as soon as the props are received from the parent class and before another render is called.shouldComponentUpdate() **Returns true or false value based on certain conditions. If you want your component to update, return true else return false. By default, it returns false.*componentWillUpdate() *– Called just before rendering takes place in the DOM.componentDidUpdate() **Called immediately after rendering takes place.*componentWillUnmount() *– Called after the component is unmounted from the DOM. It is used to clear up the memory spaces.## 22. What is an event in React?

In React, events are the triggered reactions to specific actions like mouse hover, mouse click, key press, etc. Handling these events are similar to handling events in DOM elements. But there are some syntactical differences like:
Events are named using camel case instead of just using the lowercase.Events are passed as functions instead of strings.
The event argument contains a set of properties, which are specific to an event. Each event type contains its own properties and behavior which can be accessed via its event handler only.

23. How do you create an event in React?
class Display extends React.Component({   
    show(evt) {
        // code  
    },  
    render() {     
        // Render the div with an onClick prop (value is a function)       
        return (           
           
 
 
Click Me!

 
 
 
        );   
    }
});

24. What are synthetic events in React?

Synthetic events are the objects which act as a cross-browser wrapper around the browser’s native event. They combine the behavior of different browsers into one API. This is done to make sure that the events show consistent properties across different browsers.

25. What do you understand by refs in React?

Refs is the short hand for References in React. It is an attribute which helps to store a reference to a particular React element or component, which will be returned by the components render configuration function. It is used to return references to a particular element or component returned by render(). They come in handy when we need DOM measurements or to add methods to the components.

class ReferenceDemo extends React.Component{
     display() {
         const name = this.inputDemo.value;
         document.getElementById('disp').innerHTML = name;
     }
render() {
    return(       
          
 
 

            Name:  this.inputDemo = input} />
            Click           
             
 
 
## Hello  !!!

 
 
 
        
 
 
 
    );
   }
 }

26. List some of the cases when you should use Refs.

Following are the cases when refs should be used:
When you need to manage focus, select text or media playbackTo trigger imperative animationsIntegrate with third-party DOM libraries## 27. How do you modularize code in React?

We can modularize code by using the export and import properties. They help in writing the components separately in different files.

//ChildComponent.jsx
export default class ChildComponent extends React.Component {
    render() {
        return(          
              
 
 

              
                 
 
 
# This is a child component

 
 
 
            
 
 
 
        );
    }
}
 
//ParentComponent.jsx
import ChildComponent from './childcomponent.js';
class ParentComponent extends React.Component {   
    render() {       
        return(          
             
 
 
              
                         
            
 
 
 
        
        ); 
    }
}

28. How are forms created in React?

React forms are similar to HTML forms. But in React, the state is contained in the state property of the component and is only updated via setState(). Thus the elements can’t directly update their state and their submission is handled by a JavaScript function. This function has full access to the data that is entered by the user into a form.

handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
}
 
render() {
    return (       
         
 
 

            
                Name:
                
            
            
        
 
 
 
    );
}

29. What do you know about controlled and uncontrolled components?

30. What are Higher Order Components(HOC)?

Higher Order Component is an advanced way of reusing the component logic. Basically, it’s a pattern that is derived from React’s compositional nature. HOC are custom components which wrap another component within it. They can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components. You can say that HOC are ‘pure’ components.

31. What can you do with HOC?

HOC can be used for many tasks like:
Code reuse, logic and bootstrap abstractionRender High jackingState abstraction and manipulationProps manipulation## 32. What are Pure Components?

*Pure *components are the simplest and fastest components which can be written. They can replace any component which only has a **render(). **These components enhance the simplicity of the code and performance of the application.

33. What is the significance of keys in React?

Keys are used for identifying unique Virtual DOM Elements with their corresponding data driving the UI. They help React to optimize the rendering by recycling all the existing elements in the DOM. These keys must be a unique number or string, using which React just reorders the elements instead of re-rendering them. This leads to increase in application’s performance.

React Redux – React Interview Questions 34. What were the major problems with MVC framework?

Following are some of the major problems with MVC framework:
DOM manipulation was very expensiveApplications were slow and inefficientThere was huge memory wastageBecause of circular dependencies, a complicated model was created around models and views
35. Explain Flux.

Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here only. Flux provides stability to the application and reduces run-time errors.

36. What is Redux?

Redux is one of the hottest libraries for front-end development in today’s marketplace. It is a predictable state container for JavaScript applications and is used for the entire applications state management. Applications developed with Redux are easy to test and can run in different environments showing consistent behavior.

37. What are the three principles that Redux follows?

***Single source of truth: ***The state of the entire application is stored in an object/ state tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.***State is read-only: ***The only way to change the state is to trigger an action. An action is a plain JS object describing the change. Just like state is the minimal representation of data, the action is the minimal representation of the change to that data. Changes are made with pure functions: In order to specify how the state tree is transformed by actions, you need pure functions. Pure functions are those whose return value depends solely on the values of their arguments.## 38. What do you understand by “Single source of truth”?

Redux uses ‘Store’ for storing the application’s entire state at one place. So all the component’s state are stored in the Store and they receive updates from the Store itself. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

39. List down the components of Redux.

Redux is composed of the following components:
Action – It’s an object that describes what happened.**Reducer **– It is a place to determine how the state will change.Store – State/ Object tree of the entire application is saved in the Store.View – Simply displays the data provided by the Store.## 40. Show how the data flows through Redux?

41. How are Actions defined in Redux?

Actions in React must have a type property that indicates the type of ACTION being performed. They must be defined as a String constant and you can add more properties to it as well. In Redux, actions are created using the functions called Action Creators. Below is an example of Action and Action Creator:

function addTodo(text) {
       return {
                type: ADD_TODO,   
                 text   
    }
}

42. Explain the role of Reducer.

Reducers are pure functions which specify how the application’s state changes in response to an ACTION. Reducers work by taking in the previous state and action, and then it returns a new state. It determines what sort of update needs to be done based on the type of the action, and then returns new values. It returns the previous state as it is, if no work needs to be done.

43. What is the significance of Store in Redux?

A store is a JavaScript object which can hold the application’s state and provide a few helper methods to access the state, dispatch actions and register listeners. The entire state/ object tree of an application is saved in a single store. As a result of this, Redux is very simple and predictable. We can pass middleware to the store to handle the processing of data as well as to keep a log of various actions that change the state of stores. All the actions return a new state via reducers.

44. How is Redux different from Flux?

45. What are the advantages of Redux?

Advantages of Redux are listed below:
**Predictability of outcome – **Since there is always one source of truth, i.e. the store, there is no confusion about how to sync the current state with actions and other parts of the application.**Maintainability – **The code becomes easier to maintain with a predictable outcome and strict structure.Server-side rendering – You just need to pass the store created on the server, to the client side. This is very useful for initial render and provides a better user experience as it optimizes the application performance.**Developer tools – **From actions to state changes, developers can track everything going on in the application in real time.**Community and ecosystem – **Redux has a huge community behind it which makes it even more captivating to use. A large community of talented individuals contribute to the betterment of the library and develop various applications with it.**Ease of testing – **Redux’s code is mostly functions which are small, pure and isolated. This makes the code testable and independent.**Organization – **Redux is precise about how code should be organized, this makes the code more consistent and easier when a team works with it.# React Router – React Interview Questions

46. What is React Router?

React Router is a powerful routing library built on top of React, which helps in adding new screens and flows to the application. This keeps the URL in sync with data that’s being displayed on the web page. It maintains a standardized structure and behavior and is used for developing single page web applications. React Router has a simple API.

47. Why is switch keyword used in React Router v4?

Although a **** is used to encapsulate multiple routes inside the Router. The ‘switch’ keyword is used when you want to display only a single route to be rendered amongst the several defined routes. The ** **tag when in use matches the typed URL with the defined routes in sequential order. When the first match is found, it renders the specified route. Thereby bypassing the remaining routes.

48. Why do we need a Router in React?

A Router is used to define multiple routes and when a user types a specific URL, if this URL matches the path of any ‘route’ defined inside the router, then the user is redirected to that particular route. So basically, we need to add a Router library to our app that allows creating multiple routes with each leading to us a unique view.


    
    
    


49. List down the advantages of React Router.

Few advantages are:
Just like how React is based on components, in React Router v4, the API is ‘All About Components’. A Router can be visualized as a single root component (**
**) in which we enclose the specific child routes (****).No need to manually set History value: In React Router v4, all we need to do is wrap our routes within the **
** component.The packages are split: Three packages one each for Web, Native and Core. This supports the compact size of our application. It is easy to switch over based on a similar coding style.## 50. How is React Router different from conventional routing?

I hope this set of React Interview Questions and Answers will help you in preparing for your interviews. All the best!