Integrating Redux

You all know that Redux made the difference few years ago and now a lot of developers are starting using it (mostly together with React).
What people really miss is that Redux can be used alone inside a frameworkless project (or inside a project that has a framework/library that is not React).

I - as senior - recently decided to introduce Redux inside an enterprise project to manage the big amount of data that frontend has to deal with. One of the perks of having Redux is to have a one-way-flow to store the data, which basically sets some rules among the team and the project itself. Having rules is good. You team decide which ones and after that you are good to go.

After the integration

So, after three weeks of refactor, coding, testing, bugfix and lot of changes among the application (they were a lot, trust me), the application ended up having almost TWO HUNDRED REDUCERS, all of the them listening to the same actions. I can’t share too much about why so many, but it was due to the project needs and architecture.
The application didn’t have any subscritions to the state changes, so there wasn’t a reactive change based on the data inside the Redux store. Everything was done to manage in a clean and fixed way the data inside the application.

Even though there was no UI involved, the number of accesses done to the state was a lot! Also, the number of actions to store the data was a lot. (I did put some logging and I was impressed).

Although, there were no performance regressions inside the application.

Further optimisations

Here’s the good part of the article. Have you ever thought of importing a reducer only when is needed? I don’t think so. You might say that there’s no need because Redux is fast and you are right. However, sometimes there are cases where is better to do it. Like this one.

Redux gives us an API called replaceReducer which is basically what is needed is this case.

It’s not well documented but it gives you an idea of when to use it.

And that’s what I did inside the code! We already had code splitting inside the application. There’s a key point about this API, the next reducer that you provide will replace the old one, which means that you have to provide a new object that contains also the old reducers.

Snippets

So, let’s put all these idea together and see how this idea could be applied to a real world scenario. First of all let’s make a function that it actually create a new root reducer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// two fake reducers for starter
const foo = (state = {}, action) => state;
const bar = (state = {}, action) => state;

// or `let` if you want to stick with functional/immutability
const currentReducers = {
foo,
bar
}

export function nextReducer (newReducers) {
// make some check here, here's is done with lodash. You could extend the check
if (_.isObject(newReducers)) {
// I'd suggest the latter approach
Object.assign(currentReducers, newReducers)
// .. or
currentReducers = {
...currentReducers,
...newReducers
}
}

return combineReducers(currentReducers)
}

So we have a snippet that gives a new root reducer with the new reducers that we want. How do we use it?
Let’s suppose that we are already inside a code splitted section of the application, for example the admin section. After the import() statement, we should behave like this:

1
2
3
4
5
6
7
8
// adminReducers.js where we have the reducers for the admin section
import { sideBar } from './sidebar'
import { settings } from './settings'

export const adminReducers = {
sideBar,
settings
}

Now let’s what’s inside the page where we actually need these reducers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { nextReducer } from 'path/to/nextReducer'
import { store } from 'path/to/my/store'

import('path/to/admin/main/page', ({ renderPage }) => {
// let's request our new reducers
requestAdminReducers()
.then(({ adminReducers }) => {
const newRootReducer = nextReducer(adminReducers)
store.replaceReducer(newRootReducer)
renderPage();
})
})

function requestAdminReducers () {
return import('path/to/adminReducers.js')
}

Voila’!

Comment and share

Preface

I recently started a new job in bank company as Senior UI Developer. When I first joined I was told that the the company itself was using cutting edge technologies and stuff like that. In a world like this, a Frontend Developer loves to work with such technologies, and so am I.

Once I started, I understood that everything was misunderstood. They actually use cutting edge technologies but the whole ecosystem around it is fucked up. There’s a legacy thing, there’s a half legacy thing and there’s a cutting edge technology thing that is really bad used.

Bad choice

Although, the will of the team is to refactor the whole application smoothly and gracefully using the latest technologies and least, but not last, some technology that is well maintained and there’s assurance that it will be supported for the next five years at least.

The library that was chosen at that time was made by a guy there, so when he left it wasn’t maintained anymore. Bad choice.

Right choice

The frontend has grown so fast and so big that now it has become really difficult to evaluate what to use inside an application. Five or seven years ago there was mainly jQuery and that was always the correct choice (yeah, let’s also remember Dojo).

Nowadays there are lot of choices and which is good because it forces the concurrency and the evolution between vendors; from another point of view it’s bad because the decision process is longer and harder.

I don’t want to bother you people with libraries and frameworks we have around. I want to share how I take a decision.

The factors

I will now list which are the factors that, from my point of view, have to take in consideration when choosing a library/framework.

The Context

First of all the context is really important. I have worked in a company where they didn’t want to have a Single Page application because they were running an existing e-commerce and they wanted to target the widest range of customers. Also, there was the SEO to take in consideration as they have competition and they run SEM campaigns on the different search engines.

We didn’t want to use old technologies. So I created a POC using ReactJS and demonstrated the Server Side Rendering. That was like heaven. Giving the possibility to use a cutting edge technology and providing HTML straight from the server without losing optimizations. I know that Google crawlers are able to run JavaScript but there are other crawlers that can’t. That’s something to take in consideration because the business matters.

I another job we were dealing with an internal application. A website running through a dedicated application installed in the client machines. In that case we had move leverage and a wider choice of libraries. In the the end, I arrived that there was the entire ReactJS ecosystem. Brilliant. That ecosystem was perfect because we wanted to have the ability to create/manipulate components through an external configuration and at the same time being able to have a Metadata computer engine that could be standalone.

The beauty was that were aiming to have something like Redux has: the library and the connector for ReactJS. We wanted to have the Metadata computer and metadata transmitter for React. Good times.

Now, here I have to take a big decision that will impact the internal development for the next five years.

The functionality

Choice must be taken based on what you need. You don’t use a library if it doesn’t do what you really need, or it doesn’t allow you to add custom functionality.

Every application and every company has different requirements. You must take them in consideration when you have to choose your library/framework. You can’t choose it based on the hype of the moment, especially if you are working for an enterprise company, where stability and support are important. As I mentioned before, at the moment there’s an internal library that is not supported by nobody, fixes are done internally. There’s no improvement, it doesn’t allow you to do much.

If you need a templating system application because you don’t want to make too much leverage on the JavaScript side, you will choose something like Mustache or VueJS. Definitely not a library such as React or Preact. There’s no templating involved.

If you need SSR (Server side rendering), you could use AngularJS or ReactJS or VueJS or any other library or framework that gives you that.

If you need browser testing, you will definitely karma because is quite supported by the community.

The ecosystem

That’s really important. You want to use something that is widely used and where the community and the Open Source world is happy to work with. Redux has got a really big ecosystem where they created all sort of libraries on top it. In two years the type of libraries has grown a lot and now there are add-on for every kind of purpose.

Sometimes that’s driven by the hype of the moment but you have to take in consideration that once people start playing with a tool, they understand if is manipulable or not. And if is, which is the extent.

The support

Having a person that is fully committed to the implementation and fixing bugs is really reassuring. That’s why libraries such as AngularJS and ReactJS became really popular in the past few years. They are backed up by giants so for sure they have money to pay their developers.

Sometimes another libraries are Open Source so the commitment of the people is limited to their free time because they don’t earn anything from what they are doing. We now that the community is helpful but sometimes it’s just difficult. Thankfully, if the library is successful, you will backers and sponsors somehow.

Conclusion

So, choose with calm and do not force your decision driven by the hype of the moment. Document yourself, make experiments and make sure that the library will give you want!

Comment and share

Redux is a library that recently got adopted by a lot of developers and companies to build rich UI applications. Redux rethinks an older library called Flux. I won’t bother you about the principals of Redux and so on, you can go to the main website and read them over there.

What I want to share is some tweak that I learned by developing using this library.

Multiple reducers

Assuming you all know what reducers are and you have a big application, you eventually use combineReducers to put all together all your reducers and create - what the official documentation calls - the rootReducer that you have to pass when you create the store.

1
2
3
4
5
6
// Use ES6 object literal shorthand syntax to define the object shape
const rootReducer = combineReducers({
theDefaultReducer,
firstNamedReducer,
secondNamedReducer
});

There’s also a chapter of how to go beyond the combineReducers, you can access to it here.

What’s the documentation doesn’t say clearly is that you can use combine the reducers to create also nested reducers.

You all know that the shape of the store is defined by the structure of your reducers, so each reducer can be responsible of handling each part of the state.

I will show this concept with and example.

Example - User Information

Let’s say that you want to store the information of the users inside your Redux store, and the shape of it will be something like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
// ...
products: {
// ...
},
cart: {
// ...
}
user: {
details: {
firstName: "Micheal",
lastName: "Jackson",
email: "m.j@gmailx.com",
eyes: "2",
description: "I am tall and white",
availability: "Every day"
},
settings: {
backgroundColor: "#fff",
receiveNotification: true,
categories: ['white', 'black', 'dance', 'sing']
}
}
}

Your redux store, other than this slice of user, will have also other slices; so other reducers.
In a ideal world you will have yours reducers imported and built in this way

1
2
3
4
5
6
7
8
9
10
import user from 'src/reducers/userReducer'
import cart from 'src/reducers/cartReducer'
import products from 'src/reducers/productsReducer'
import { combineReducers } from 'redux'

export default combineReducers({
user,
cart,
products
})

As you can see it’s a simple object. But, if you changed just one value inside the array categories, your reducer will be quite complicated because you have to maintain intact the rest of the state.

What if I told you can create nested reducers

Exactly! You can create reducers that will be responsible of a subsection of the parent reducer!

Let’s create a reducer responsible of the settings and a reducer responsible of the details

1
2
3
4
5
6
7
8
9
10
// userDetailsReducer.js

export default function userDetailsReducer (state = {}, action) {
return state
}

// userSettingsReducer.js
export default function userSettingsReducer (state = {}, action) {
return state
}

Now, the new userReducer will be something like this. We will use combineReducers to create a new reducer using the other two reducers that we just create

1
2
3
4
5
6
7
8
9
// userReducer.js
import details from './userDetailsReducer'
import settings from './userSettingsReducer'
import { combineReduers } from 'redux'

export default combineReducers({
details,
settings
})

You want to have a reducer responsible of the categories? You can follow the same pattern but bear in mind that if you did that, you would need make also backgroundColor and receiveNotification reducers!

Let’s see

1
2
3
4
// settingsCategoriesReducers.js
export default function settingsCategoriesReducers (state = {}, action) {
return state
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// userSettingsReducer.js
import categories from './settingsCategoriesReducers'

// @reducer
function backgroundColor (state = {}, action) {
return state
}

// @reducer
function receiveNotification (state = {}, action) {
return state
}

export default combineReducers({
backgroundColor,
receiveNotification,
categories
})

That’s how you create nested reducers. It’s easy and the separation of concerns is more granular and easier to understand.

Comment and share

I recently implemented some big optimizations for the company that I work for and I wanted to share with you how I tackled the topic step by step. The solution uses dynamic import and code splitting.

The application uses reactjs as UI library, but the concept of splitting the code can be applied to every application.

I always try to use the latest technologies and features in order to bring the highest level of quality for my customers. The application that I work on is a metadata driven application. What does that mean? It means that all the components that the application has to render will dictated by some metadata coming from the server. So by default the application doesn’t know what to render.

The application implements a mapping which is basically an object that maps the components to render:

1
2
3
4
5
6
7
8
9
10
11
12
// mapping.js
import ComponentA from 'src/path/to/ComponentA'
import ComponentB from 'src/path/to/ComponentB'

const components = {
ComponentA,
ComponentB
}

export default function getComponent(type) {
return components[type]
}

Inside the application there is a component that will be in charge of getting the component based on the definition of the metadata and it will render it. There is no rocket science behind it so I will skip this step.

Everything was synchronous and the application needed to load internally all the components before getting the first document.

Code splitting

Webpack always had a feature for code splitting called require.ensure.

I wanted to use this feature but, there is more! Webpack introduced a new approach using a function called import() which will be very soon proposed as a standard, probably inside JavaScript ES2018. If you want to have more information about how to you use the function, check this article from 2ality.

This function tells to Webpack

Get this very file specified inside the path that I give you as input and put it inside a different file that will be called ‘chunk’. Inside this chunk, also append all the dependencies that it needs

Webpack has a limitation though, the import is done at compiling time, not at runtime (there is no way at the moment to ‘guess’ which file to load). But that’s fine, I just want to implement the code splitting

1
2
3
4
5
6
7
8
9
// mapping.js

export default function getComponent(type) {
switch (type) {
case 'ComponentA': return () => import(/* webpackChunkName: "ComponentA" */ 'src/path/to/ComponentA')
case 'ComponentB': return () => import(/* webpackChunkName: "ComponentB" */ 'src/path/to/ComponentB')
default: return undefined
}
}

You see that comment named webpackChunkName? Well, that’s a recent feature implement inside version 2.4.0 of webpack. This gives you the chance to give a name to the chunk. This feature could potentially deprecate the require.ensure.

The component that will be responsible of rendering those components will look like this

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// RenderComponent.js
import getComponent from './mapping.js'

class RenderComponent extends React.Component {

constructor (props) {
super(props)
this.state = {
component: null
}
}

componentDidMount () {
const { metadata } = this.props
this.fetchComponent(metadata)
}

fetchComponent (metadata) {
const resolver = fetchComponent(metadata.type)
if (resolver) {
resolver()
.then(Component => this.setState({ component: <Component /> }))
.catch(err => throw new Error(err))
}
}

render () {
const { component } = this.state
if (!component) {
return null
}
return (
component
)
}
}

In this way, when webpack will compile the code, will create different chunks separated from the main bundle, they will have the name that I specified and will be loaded only if they are needed from the metadata!

Comment and share

In the previous article I made a superficial introduction to webpack, what is its purpose and how to set it up with the minimum configuration.

Here I want to share some of the problems that I had and how I solved them.

Webpack is really fast and the guys that develop it always try to hit the benchmarks in terms of speed of the builds but sometimes it can’t keep it, especially when your project has tons of modules that it has to process, decide the dependency order, fetch, etc. At some point you could start see some slowness in your build, especially in development mode. When you work on your dev server, you want you build to be fast, hot reload your code as fast as possible. When I worked on a code base of around 2.000 files, every save change was taking around 10 seconds to hot reload, which was affecting the efficiency of the developers in a bad way.

DllPlugin

Don’t get fooled by its name, it doesn’t have anything in common with Windows! This plugin creates a library (JSON file) that will be used by webpack to create a set of references to your modules.

This plugin is meant to be used to build once in a while the vendors of the application. Why? The vendors are less likely to change during the developments of the application, webpack doesn’t need to build them every time that we change one single line in our code base. I repeat, webpack is really fast and creates lot of optimizations, you want to use this plugin we you start seeing the new rebuild of your application around two seconds.

I use this plugin in development mode; you can’t use in production mode.

Here’s the code to set up your DllPlugin with your vendors. First of all I create two different config files for webpack. One for the vendors and one for your development environment.

1
2
3
4
5
6
7
8
9
// vendors.js
module.exports = [
'babel-polyfill'
'react',
'lodash/isEmpty',
'redux'
'redux-saga',
'redux-saga/effects',
]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// webpack.config.vendors.js
const webpack = require('webpack')
const path = require('path')

module.exports = {
entry: path.resolve(__direname, 'vendors.js'),
output: {
// the name of the output file
filename: 'vendors.bundle.js',
// we will store it inside the 'src' folder
path: path.join(__dirname, 'src'),
// the library name is important. Webapck will use this
// name to create all the references to this file and the
// manifest generated
library: '[name]_lib'
},
plugins: [
new webpack.DllPlugin({
// The path to the manifest file which maps between
// modules included in a bundle and the internal IDs
// within that bundle
path: './[name]-manifest.json',
// The name of the global variable which the library's
// require function has been assigned to. This must match the
// output.library option above
name: '[name]_lib'
}),
]
}

DllReferencePlugin

In order to read this vendor, we have to use another plugin called DllReferencePlugin. Below a simple snippet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// webpack.config.dev.js
const path = require('path')
const webpack = require('webpack')

module.exports = {
entry: path.resolve(__dirname, 'src/app/index.js'),
output: {
filename: 'bundle.js',
path: path.join(__dirname, 'src'),
},
plugins: [
new webpack.DllReferencePlugin({
context: '.',
manifest: require('./vendors-manifest.json')
}),
]
}

Remember to import your vendors bundle before the bundle of your application.

1
2
3
4
5
6
7
8
9
10
11
12
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src='vendors.bundle.js'></script>
<script src='bundle.js'></script>
</body>
</html>

It is worth to have a look inside the manifest that the plugin generates. As you can see there are different references that webpack will use to speed your build. That means, de facto, that your vendors will be built only once! So, if you upgrade your vendors or you install new vendors, remember to update your manifest again or you won’t see the changes applied to your vendors.

PrefetchPlugin

When I was working on a large scale project, the DllPlugin didn’t help that much, unfortunately. The application scale was really big, the quantity of HOF (High-order Functions) was that high that it was asking to webpack lot of computatino, especially retrieving the path of each file every time it was running the Hot Reloading. That’s where I decided to introduce the PrefetchPlugin. The link point to the old version of webpack because the new website doesn’t provide a documentation of this plugin yet.

The plugin basically puts into memory the resolution of a specific file so, when when webpack has to resolve it again, it already knows where to go. The usage of this plugin sped up the build drastically.

The thing is that I had to provide tons of files and in order to do that, I came up with a code like this

Once you have the lists of files inside your array, just follow the snippet:

1
2
3
4
5
6
7
8
9
10
11
12
 const webpack = require('webpack')
const plugins = []
files.forEach(file => {
plugins.push(new webpack.PrefetchPlugin(file));
})

module.exports = {
// ...
plugins: [
...plugins
]
}

I hope this tips would help you to help your developement environment

Comment and share

It’s been already few years that the frontend in general started to use bundlers. These tools allow you to have different files and, thanks to some logic, retrieve the dependencies of each file.
I personally started with RequireJS which was the first, as much as I recall, to allow you to create a dependency system of your external files. I won’t bother you of how this works. Let’s just say that time passed and new tools emerged.

One of the most famous and successful tools is webpack, a bundler tool that runs on nodeJS and allows us the bundle all our files one single file (bundle) based on the dependencies that we have in our application.

Webpack is getting really popular because it gives to the developers lot of tools to build the application and it has a plugin system really flexible:

  • hot reload of the files (no more F5 or CTRL+R)
  • wide range of plugins
  • development server
  • code splitting strategy

Due to the wide range of settings and tools that webpack gives to us, at the beginning is not easy to set up a starting project with this tool. I still rememeber at the beginning, when the tools was at version 1.0 and the documention was really poor and confusing! Hard times!

Now, people have more knowledge, the documentation is better and we have more resources. I will more experience and tricks here.

Setting up

Create your project folder and set up npm and webpack

1
2
3
4
5
mkdir ecommerce
cd ecommerce
npm init
# ...
npm i --save webpack

Sweet, now let’s create a config file and a starter point, also called entry point

1
2
3
4
5
6
7
8
touch webpack.config.js
mkdir src
mkdir dist
cd src
touch index.js
touch alerts.js
cd ../dist
touch index.html

This is how your webpack.config.js should look like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var path = require('path');

module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/dist'),
filename: 'bundle.js'
},
resolve: {
modules: [
'node_modules',
path.resolve(__dirname, '.')
}
}
}

For the sake of the example, let’s write something in our two modules

1
2
3
4
5
6
// index.js
import showAlert from './alerts.js'

document.addEventListener('DOMContentLoaded', function() {
showAlert('Page loaded!');
}, false);
1
2
3
4
// alerts.js
export default function showAlert(message) {
alert(message);
}

That’s it, now open your package.json file and add the following script and run it:

1
2
3
4
5
{  
"scripts": {
"build": "webpack --config webpack.config.js"
}
}

1
npm run build

We create our first bundle.
I will explain the configuration:

  • entry: the file/files where you want to start importing your files (or modules). It can be a string, an array or an object
  • output => path: where to save the output. Remember that we can have multiple files (but not here in this configuration)
  • output => filename: the name of the final file. There’s a proper configuration in case you are setting multiple entry points and naming them in different way
  • resolve => modules: here you telling to webpack this ‘webpack, when I import my modules, you have to look for them in the folders provided in this array’. In this case our folders are ‘node_modules’ and the current folder

Now, inside your index.html file, let’s write this

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>webpack example</title>
</head>
<body>

<script src='bundle.js'></script>
</body>
</html>

You are up and running for webpack!

Comment and share

First Post

in personal

Welcome to my new version of the ematipico blog!

This new version is developed with Hexo, a NodeJS blog platform to create smoothly blogs with static pages.
It is really easy to use and there is no hassle. Furthermore, there is no need to use any kind of database or whatsoever. Niche!

The previous blog was all built in-house but I realised that it is not for me anymore, it requires lot of time to develop the CMS, maintain the frontend and writing the posts.
After a while I got tired and I could not keep it up anymore.

I hope to be able to share more information from now on!

Comment and share

  • page 1 of 1

Emanuele Stoppa

Programmer, Gamer and music listener


Senior UI Developer, Contractor


Dublin