Redux (on process)

Redux helps us to create a single source of truth, to group the state of our components in a JavaScript object separate from our containers or components. We can get and update the state we want connecting our component to this separate object. We wrap our component tree so we have access to Redux functions. We can grab the state we want  and Redux will map it to our component as a prop.

We keep our state in the store. To update the data we have in the store we have to send an action, with a type and maybe a payload to the store, who send it to our reducer that holds information for how Redux can update that state depending on the type of the action. Actions and reducers are POJOS.

Any component ‘connected’ will be able to modify the state using an action we’ve defined.

We keep our state in one JS object, the store, and our actions and reducers on another two different JS objects.

Reducers will need a state and an action, and Actions will need a type property and an optional payload.

When we update the state it is very important not return null or undefined, that’s why we use a default return.

Reducers are pure functions. Our reducer never updates the previous state, creates a new state object.

The reducer updates the state but doesn’t persist these changes. To persist these changes we can reassign the return value of the reducer to a variable. We can encapsulate that in a function, in dispatch.

We dispatch an action to the store, who calls our reducer and returns to us a new state.

We create a store function ( which is a closure) to encapsulate the state (so we don’t change it by mistake in other places of our code), to encapsulate our dispatch function and to encapsulate a function to get the new state (getState). When we call this store function we get an JS object with our dispatch function as a method, which has access to state.

Redux works by having an action dispatched, which calls a reducer, and then renders the view.

Using Redux in an React app

To install Redux in my app I type into my console:

npm install --save redux 

npm install --save react-redux

npm install --save redux-thunk

  1. Initialize my store in index.js using createStore Redux function and pass it down to my top-level <App /> container.

To have access to the store in any of our components we import the react-redux function connectinto the component where we want to have access.

If we want some state we can use:

We can access these data as: this.props.whatEverWeWant. We can create our own customised props playing with the data of our store, with the state with have created in the state of our reducer. For example here we have whatEverWeWant only in the state, but if we want a prop like numberOfwhatEverWeWant we don’t modify our reducer, we can add numberOfwhatEverWeWant: state.whatEverWeWant.length¬†in our mapStateToProps and that’s it!

If we want to dispatch an action and update our store we do something like:

Then to be able to debug I have installed redux-devtools-extension and add this code to my index.js:

connect function

connect function listen to changes in the state.

When a change occurs it calls the function mapStateToProps()where we specified the info we want from the state and gives it to us as a prop. We have to write this function ourselves. This function¬†has access to the entire store’s state.

And then we finally specify which component of our app we are providing with this data.

If we don’t give a second argument to connect,(mapDispatchToProps would be the one), connect gives us the prop dispatch for free! This second method¬†allows us to customise how we send actions to our reducer. If it is not for this second argument, our component wouldn’t know anything about Redux and our store.

One pattern is to only connect Container components.

Redux Actions

Actions are POJOs that has a property of type.

We dispatch our action to the store (whit the dispatch method), the store passes the action to the reducer, that checks the type property to see what he has to do, what changes will make to the state. Remember reducer takes two parameters, state and action.

We should wrap our actions into functions, in case these actions have some parts that will need to change or add different payload properties (like a user to the list of user), and we pass those functions to the dispatch method. Those functions are called action creators.

We keep our React application separated from our Redux application by using the Provider component and the connect() function.

We don’t reference our store in our components. mapStateToProps() and mapDispatchToProps() allow us to separate concerns. The first one helps us to manage our state and the second one is an action creator, mapped as a prop. Our components only display state, they don’t manage it.

We pass these two functions to connect(). When connect()' executes it calls the first function, mapStateToProps, and pass it the current state. Then it calls the second function and passes it the dispatch function. The dispatch function takes an action, so don’t forget to import the action :). Then we can access this dispatch function as a prop.

Refactoring these methods.

This is equivalent to:

We can pass an anonymous function as first argument to connect, and we can pass a function, if we do this we have to do it as before, or an object and connect will pass it the dispatch function. If we pass an object, this one needs to contain key/value pairs for each action creator we want to become props. As of JavaScript ES6, when we have an object with a key and value with the same name, we can use the shorthand syntax and write { addItem }.


It combines the different reducers we pass to it into one single reducer that we pass to our store.


npm (Node Package Manager) is a command line tool and helps organizes and install packages in our JS project.

* Node is a JS runtime, to run JS locally in your computer instead of in a browser.

npm is automatically installed along with Node.js so to check if you already have it in you computer run:

node -v

If a version doesn’t appear you can use the Node Version Manager to install Node.js.

To check the version of npm:

npm -v

To update it:

npm install --global npm

npm works with the package.json file and has a command to create it: npm init

The package.json file includes info about the project and tells to npm which packages are required for the project. When we run npm install in a project with a package.json file, npm downloads and install all packages listed in the file from

If you are working in a local environment running npm install creates the folder node_modules, with all the downloaded packages.

To install more packages than the listed in the package.json, run:

npm install <name_of_the_package>



React is a front end web framework built entirely out of JS. We use JSX, an extension of vanilla JS, to write our components.

Why React?

Using components allow us to separate functionality and code.

It has a virtual DOM, to render faster.

React includes Babel that compiles JSX down to React.createElement() calls and Webpack, the module that bundles the JS files of the project.

Easy to create a new react app and run npm install and npm start.


Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called ‚Äúprops‚ÄĚ) and return React elements describing what should appear on the screen. –

*React elements are the objects created by React.createElement()

Types of components

  • If props and state are not changing and we don’t need special work updating our component we can use PureComponent.
  • If we don’t need to use state and lifecycle methods we can use a functional component. In order to use state we have to inherit from Component, and functional components don’t do that.

Functional components don’t have state but have props, we have to explicitly pass them as the argument for the function.

We can use object destructuring and extract values from props.

The components are the files written using JSX. You can import one file/component into another component and make it its parent component so its parent can render it inside an element.


*Always start component names with a capital letter.

*must never modify its own props. For that, use the state.

All React components must act like pure functions with respect to their props. –reactjs

*I would start writing the component as a function component and if class component features, like .state, are necessary, then change it to a class component.

Container and presentation components

So we have talked so far about functional, class and pure components. Container and presentational components are not different types of components, they are a way to organise your react app.

Presentational components usually receive props and display content.

Containers keep more complex logic, dealing with state and usually are class components.

Render a component

In this example I render the App component.

Importing from the node_modules folder and the src folder, exporting and the Component Chain

When a component doesn’t have an export means that is the top of this chain.

*For an optimization of udpating, React recommends using React.PureComponent instead of React.Component. PureComponent doesn’t have access to shouldComponentUpdate¬†because he will check for changes in props and state and update if necessary.

Props and state

Props are arguments passed into React components. They are like function arguments in JS and attributes in HTML. To send the props into a component, we use the same syntax as HTML attributes. React props are read-only. A component can change its own state but not its props. The parent who is passing the props can change them.

Default values for props:

State is similar to props, but it is private and fully controlled by the component. React components has a built-in state object. The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders.

The state object is initialised in the constructor method.

We should call super() in the constructor since we are inheriting from another class via the extends keyword.  We set initial state in the constructor because it runs first.

We can change the state using setState(), which will re-render the component:

When we want to update our state based in the previous state. Never use a this.state inside a setState. We can pass a function to setState that, when called inside setState will be passed the component state from when that setState was called (previous state) and the return value will be the new state (important use return!).

React’s Event System

React uses basic HTML events and wrap them in the SyntheticEvent to make sure events are handled the same way across all browsers.

setState() sets state asynchronously.

Update a nested state

We can not modify props only the state. Every component can modify its own state using setState, but what if a child want to modify the state of its parent? In order to do this we can use a callback. The parent component can pass down a callback function to its child where its state is modified. The child will have access to the cb inside the props being passed to it.

Event pooling

When the event fires, the event data is sent to the callback. If we need to use this data in an asynchronous way we can store it in a variable or we can make the event persistent (event.persist()).


When you have a form in React you usually want to write a JS function to handle the submission and have access to the form data. There are two different ways to control the form’s data, the controlled and the uncontrolled form,¬† but the safest is using a controlled form.

How to know if the component is controlled or uncontrolled? If the input has a value, it is a controlled component and if the input has a defaultValue is an uncontrolled component.

Controlled forms store their input values in the state. With a controlled component we can control user input and show errors. How do we add the input data to our state?

  1. Adding a value attribute to our input like <input type="text" name="query" onChange="{this.handleChange} value="{this.state.query}"/> or for radio and checkbox types, the checked attribute:
  2. and then updating our state with the setState method inside an onChange event listener that will fire every time the value of the input changes.

Having the form data in our state means that it is easy to pass them down as props to other component or pass them to a parent component using a function callback supplied in props.

Form with multiple inputs

We can access the attributes of our handleChange function and get different info. For example if we give to our input an attribute name we can access it via that means that we can create a more abstract handleChange function and use it without having to write a different function to handle the changes for each input of our form, in case we have a form with more than one input like the one in the example. In order to do so we have to make sure that the name value is equal to the key/keys of our state.


How to render a list of elements:

We should include a key (string) in our list of elements.

A good rule of thumb is that elements inside the map() call need keys.

React component methods

  • render()
  • Error handling during rendering, in a lifecycle method, constructor of any child component:
    • static getDerivedStateFromError()
    • componentDidCatch()
  • Other APIs:
    • setState()
    • forceUpdate()
  • Class properties:
    • defaultProps
    • displayName
  • Instance properties:
    • props
    • state

The render() method is necessary for a class component to be valid, the other ones are optional.

React component lifecycle

Component lifecycle: creation(mounting), updating, and deletion(unmointing).

React has special built-in events relating to the component lifecycle, the lifecycle hooks/methods.

  • Pre-mounting:
    • constructor(). Where we create the initial state of the component.
  • Mounting:
    • static getDerivedStateFromProps(props, state). I gives us access to state and props.
    • render(). It returns JSX so React can insert it into the DOM.
    • componentDidMount(). Where we set up long-running or asynchronous processes such as fetching or updating data.
  • Updating:
    • static getDerivedStateFromProps(props, state). Where we can check state changes prior to an update. Use it when you want to modify the state based in the new props.
    • shouldComponentUpdate(nextProps, nextState). Invoked before the re-render. We can compare here if there are changes in the props or the state and avoid an unnecessary re-rendering.
    • render().Here the next props and the state became available as this.props and this.state. the component gets rendered into React’s virtual DOM.
    • getSnapshotBeforeUpdate(prevProps, prevState). Just before React commits content from its virtual DOM to the actual DOMReturns a snapshot that can be used in the next hook. You can get info like the scroll position.
    • componentDidUpdate(prevProps, prevState, snapshot). We can take some actions here without triggering a re-render of the component, like focusing on a specific form input. Here we have access to the previous and the current props and state and we can use this hook to update any third party libraries if they need to update due to the re-render.
  • Unmounting:
      • componentWillUnmount(). To clear any stuff we set up in componentDidMount.And avoid automatic data fetching for example that we don’t want.


Sending fetch requests

We can send a fetch request when the component is mounted, in the componentDidMount hook or we can tie it into an event.

Another way to organise the fetched data is using the container component pattern. Here it is a good link about it.

React Router

React router uses client-side routing, not server-side routing.

With Client-Side routing, it is now the responsibility of the Client-Side-Code to handle the routing, fetching and displaying of the data in the browser instead of the server.

Using pushState(state, title, url).

React and Babel

Babel is a compiler that makes all JS versions, even JSX, and emit a common one.

React and Webpack

Webpack combines different JS files, pre-bundles them together into a single file, to make less http requests to the server.


React create during the first render the current tree,  that looks like the current DOM, and when updates cause a re-render it creates the workInProgress tree, representing how the DOM will look. React uses a diffing algorithm to check for differences and if necessary uses this second tree to update the current tree and the DOM .


Problem from Hackerrank.

My solution:


Mini-Max Sum

Problem from Hackerrank.

My solution:



Problem from Hackerrank.

My solution:


Plus Minus

Problem from Hackerrank.

I was making the mistake of checking if the index was bigger or smaller than zero, instead of checking the value of the integer in that index. I was comparing i instead ,arr[i].

My solution:


Diagonal Difference

Problem from Hackerrank.


Simply Array Sum

Problem from HackerRank.

Easy problem but I got confused with the index of the array and its value. I was adding i to my result variable and not ar[i].


JS Cheatsheet (work in process)

JavaScript engine makes multiply passes over the same code:

  1. First pass to parse the syntax. During this pass the engine undertakes a process called automatic semicolon insertion.
  2. Second pass to initialise variables and functions and store them in memory. Hoisting: is a JS default behaviour of moving all declarations to the top of the current scope ( to the top of the current script or the current function). Variables and constants declared with let or const are not hoisted.
  3. The third pass is to actually execute the code line-by-line.

First and second passes are called the compilation phase and the third phase is called the execution phase.


No matter what combination of types you write, JS won’t throw an error and will return something, even a non sense and weird something.

  • alert(“Hola!”);
  • console.log(“Hola!”);
  • console.error(“Hola!”);
  • console.warn(“Hola!”);
  • console.table

  • try statement lets you test a block of code for errors.

catch statement lets you handle the error.

  • throw statement lets you create custom errors.

  • finally¬†statement lets you execute code, after try and catch, regardless of the result.


  • Unit testing
  • Integration testing
  • End-to end testing


Data types:

Everything in JavaScript is data except:

  • operators:+, -, <=, etc.
  • reserved words:function, for, debugger, etc.

A basic type checking with the typeof operator: typeof(42);

The JS’s seven data types:

1.Numbers (primitive data type).

2. strings (primitive data type).

We use ‘single quotes’, “double quotes”, or `backticks.

String concatenation:

3. Booleans (primitive data type).

The following values are falsy:






'', ""

Every other value is truthy.

4.Symbols(primitive data type) are primarily used as an alternate way to add properties to objects.

5. Objects:

JS defines 5 types of primitive data types: string, number, boolean, null, undefined. All JS values, except primitives, are objects. In JS almost everything is an object: booleans, numbers and strings, if defined with the new keyword can be objects. Primitive data types represent single values, such as a number, a string or false, instead of a collection of values.

var x = new Boolean(false);

//typeof x returns object 

JS objects: dates, maths, regular expressions, arrays, functions and objects.

Objects are similar to a hash in Ruby or a dictionary in Python. Arrays in JS are objects too.

All keys in an object are strings.

Access a value stored in an Object:

Add a property to an Object:

Delete an property


Add an element:


Delete an element:


6. Null (primitive data type). Null is an absent object, but when called with typeof returns object.

7. Undefined (primitive data type). It is like a “not yet assigned a value”.

Spread operator (…)


Start with a lower case and don’t use spaces, use camelCase.

Mind reserved words or future reserved words.

We can package both of the initialisation steps, declaration and assignment in a single line of code:

Differences between var, const and let.

*Variables declared without a const, let, or var keywords are always globally scoped. You can avoid this using strict mode.


var is function scoped. The scope is limited to the function within which it is defined. If it is defined outside any function, the scope of the variable is global. They are not block-scoped.

Can be reassigned.

var comes with a ton of baggage in the form of scope issues, for example, with var no error is thrown if you declare a variable twice.


let is block scoped. The scope is limited to the block defined by curly braces {}.

Can be reassigned.


const is block scoped. The scope is limited to the block defined by curly braces {}.

Can not be reassigned to anew value, but can be mutated.

Conditional statements:


A function is an object that contains a sequence of JavaScript statements.  Declaration:

Function calling or execution:

Parameters. They are locally scoped variables that are usable, scoped, to inside the function. Here name is our parameter.

JS will assign the argument of “Diana” to the parameter name when this function is called.

Function declaration vs function expression

The difference lies in how the browser loads them into the execution context.

Function declarations load before any code is executed.

Function expressions load only when the interpreter reaches that line of code.

If you try to call a function expression before it is loaded you get an error.

Arrow functions:

Arrow functions do not have their own this, it uses  whatever this is defined within the scope it is in.

Looping and iteration:

Iteration is the number of times a loop can be executed, while loop is the code which generate or causes expressions to be iterated.

Looping is the process of executing a set of statements¬†repeatedly until a condition is met. It’s great for when we want to do something a specific number of times (for¬†loop) or unlimited times until the condition is met (while¬†loop).

Iteration is the process of executing a set of statements once for each element in a collection.

Creating object with JS


  • S.O.L.I.D.: 5 principles of Object Oriented Design with JS.
    • S: Single responsibility principle.
    • O: Open closed principle. Open for extensions and closed for modifications, we shouldn’t introduce breaking changes to existing functionality.
    • L: Liskov substitution principle. Every subclass should be substitutable for their parent class.
    • I: Interface segregation principle. A client should never be forced to implement an interface that it doesn’t use or clients shouldn’t be forced to depend on methods they do not use.
    • D: Dependency Inversion principle. Entities must depend on abstractions not on concretions. Importance of higher-order functions.
  • ES6: “ES” ECMAScript, the official name of the JavaScript specification (Harmony – ES5)
  • Higher Order function: Function¬†that may receive a first-class function as an argument and can even return a function.
  • First-class functions: Functions that are treated as objects or assignable to a variable.
  • AJAX: Process of making requests for additional data became known as Asynchronous JavaScript and XML, or AJAX.
  • Closure: When a function is able to remember and access its lexical scope even when that function is executing outside its lexical scope.¬†A closure is a feature in JavaScript such that a function holds onto the variables that it had access to when it was declared. Closures can be used to declare functions that have specific variables always defined. JavaScript developers also take advantage of closures to encapsulate data, as we can declare our functions in such a way that the data is only accessible from the returned function, with no way to overwrite the variables captured by the closure.

  • Lexical scope: Where functions and variables are declared.
  • Hoisting: It is JS’s default behaviour of moving declarations to the top of the current scope. Let and const are not hoisted. During a compilation, every declaration ( of variables or functions) are added to the relative scope. Function declaration hoisting differs from variables as the content of the function get hoisted too.

  • Scope: Where something is available. In JS, where declared variables and methods are available within our code. Global scope, function scope, block scope, scope chain, lexical scope ( where functions and variables are declared).

  • Recursion: A recursive function is a function that calls itself.

  • Call back: When we pass a function into another function where in it might be invoked, we refer to the passed function as a callback.

  • forEach: Differences between map and forEach:
    • forEach():¬† It simply calls a provided function on each element in your array. This callback is allowed to mutate the calling array.¬†It returns undefined.¬†forEach()¬†affects and changes our original Array.¬†forEach()¬†may be preferable when you‚Äôre not trying to change the data in your array, but instead want to just¬†do something¬†with it ‚ÄĒ like saving it to a database or logging it out.
    • map(): creates a new array with the results of calling a provided function on every element in the calling array. The difference is that¬†map()¬†utilises return values and actually returns a new Array of the same size.¬†map()¬†returns an entirely new Array ‚ÄĒ thus leaving the original array unchanged.¬†And¬†map()¬†might be preferable when changing or altering data. Not only is it faster but it returns a new Array.

  • Statement vs expression: A statement is a unit of code that accomplish something but does not produce a value. An expression is a unit of code that produces a value.
    • statements: variable declarations, iteration, control flow, debugging.
  • this:¬†keyword that refers to the object it belongs to. Safer if using arrow functions, because arrow function uses whatever¬†this¬†is defined within the scope it is in.
    • This, inside a standalone function will refer to the global object.
    • Outside any function, this refers t the global object, in web browsers this is window.
    • Inside an object method, this refers to the object that received the method call.
    • Inside an standalone function, even one inside a method, this will default to the global object.
    • When using strict mode in a standalone function, as we do inside classes, this will be undefined.
    • We can use .bind, .call and .apply to control the value of this.