REACT & REDUX – tracing the steps…

THE NORMAL REACT STUFF

  1. Develop the code which: reads an input and writes to (local) state upon submit.
  2. the render() reads from (local) state and lists out the data.
  3. This will eventually be the PRESENTATION layer of our App.

THE REDUX STUFF

  1. Create a storewhich ties to a reducer
  2. Create a reducerwhich performs action based on the type
  3. Normally, we dispatch the (Add/Edit) function(s) using store(dot)dispatch
  4. Don’t dispatch the function(s)for now

THE REACT meets REDUX STUFF

  1. Presentation Component has all the details related to the UI/UX;
  2. mapStateToProps
    • helps MAPS the STATE to PROPS (when we replace STATE by PROPS)
    • This is for FETCHING Data from the Redux Store
    • put the properties here which you want to return and print on the screen
    • This is where you replace this.state.propertyName by this.props.propertyName
    • here we declare what pieces of state you want to have access to (we got access to message only)
  3. mapDispatchToProps
    • helps MAPS the DISPATCH to PROPS (when we replace STATE by PROPS)
    • here we declare which action creators you need to be able to dispatch (we got access to subitNewMessage only)
    • in React: upon a click event, we used to update the state like setState( messages: this.state.messages.concat(currentMessage) )
    • Now, to use Redux: We do props.submitNewMessage(currentMessage)
    • submitNewMessage didn’t exist before, this is defined inside the mapDispatchToProps function
  4. connect
    • used for bringing it all together
    • Container is used to connect state & dispatching with the

basic Code for react redux (as per listing above)

 

Redux – Immutability

Methods for enforcing the key principle of state immutability in Redux. Immutable state means that we never modify the state directly, instead we return a new copy of the state.


const immutableTypesDefaultState = { lastInput: '', messages: ['message1', 'message2', 'message3'] };
const immutableTypesReducer = (state = immutableTypesDefaultState, action) => {
switch (action.type) {
case 'ADD_BAD': { /* BAD !!! PUSH IS STATE MUTATION */
// this.setState({ messages : this.state.messages.push(action.input)});
//console.log('looking to push ['+action.input+'] into messages array');
var newArray = state.messages;
newArray.push(action.input);
return { lastInput: action.input, messages: newArray };
}
case 'ADD_GOOD_NORMAL': { /* GOOD !!! THIS IS NOT MUTATION */
//console.log('looking to add ['+action.input+'] via concat');
var anotherArray = state.messages;
anotherArray = anotherArray.concat(action.input);
return { lastInput: action.input, messages: anotherArray };
}
case 'ADD_GOOD_SPREAD': { /* GOOD !!! THIS IS NOT MUTATION using the SPREAD operator */
//console.log('looking to add ['+action.input+'] via spread');
var yetAnotherArray = [...state.messages, action.input];
return { lastInput: action.input, messages: yetAnotherArray };
}
case 'REMOVE_ITEM': { /* GOOD !!! THIS IS NOT MUTATION using the SPREAD operator */
//console.log("requesting to remove an object on index:",action.input);
var slimmedArray = state.messages.filter(val => val != state.messages[action.input])
return { lastInput: action.input, messages: slimmedArray };
}
case 'OBJECT_ASSIGN': { /* GOOD !!! THIS IS OBJECT ASSIGNMENT WITHOUT MUTATION */
//console.log("requesting to change an object while enforcing state immutability with:",action.input);
var changeObject = Object.assign({}, immutableTypesDefaultState, { lastInput:action.input} );
return { lastInput: action.input, messages: changeObject };
}
default: return state;
}
}

const ImmutableTypesStore = createStore(immutableTypesReducer);
console.log(ImmutableTypesStore.getState());

setTimeout(function () {
ImmutableTypesStore.dispatch({ type: 'ADD_BAD', input: 'sample input for push' });
console.log(ImmutableTypesStore.getState());
}, 2000);

setTimeout(function () {
ImmutableTypesStore.dispatch({ type: 'ADD_GOOD_NORMAL', input: 'sample input for Good via concat' });
console.log(ImmutableTypesStore.getState());
}, 4000);

setTimeout(function () {
ImmutableTypesStore.dispatch({ type: 'ADD_GOOD_SPREAD', input: 'sample input for Good via spread' });
console.log(ImmutableTypesStore.getState());
}, 6000);

setTimeout(function () {
ImmutableTypesStore.dispatch({ type: 'REMOVE_ITEM', input: 1 });
console.log(ImmutableTypesStore.getState());
}, 8000);

setTimeout(function () {
ImmutableTypesStore.dispatch({ type: 'OBJECT_ASSIGN', input: 'Object.assigned was used for this' });
console.log(ImmutableTypesStore.getState());
}, 10000);

Audit score on Google Lighthouse (PAK)

Optimizing website with zero budget: my journey

TL;DR

I optimized the beta version of my website to some really high scores on leading website performance auditing tools; I share my experience with these tools. Check the banner image or check the website at https://beta.akberiqbal.com.

What makes a great website?

For those who give more importance to visual design, it can be anything from a flashy design with high-resolution images and video to others who prefer a minimalist, simple design. For a more educated consumer, it would be a website which is tailored for its visitor, covered generally as usability or user experience, it is a detailed topic, put simply as the ‘ease with which a consumer can get the information they need’.

For millennials and mobile users, it would be speed. Users on mobile account for more than half of all visits to websites and for these users design needs to be responsive, size should be optimized for 3G connections and usability is a metric which becomes more important on a mobile’s real estate.

For some users and governments, accessibility would be a must-have and it helps ensure that the web is inclusive of all, given the numbers of this demographic. We have all heard that content is king, and with proper search engine optimization, it brings more visitors to a website.

For a web developer, what would be a great website?

There are many tools out there which try to answer this very question; It is primarily done by benchmarking and setting best practices. Among the many tools out there, I will only discuss a few which are closer to being at the top of this pile in my opinion and which I used to develop an optimized ‘beta’ version of my website.

To make things interesting, the budget for this website optimization exercise was $0. To this day, I only pay for the domain and hosting only. No other paid services at all. Following will be a brief introduction and experience over my journey with these tools.

Google Lighthouse: a very comprehensive tool, built for developers and part of the Google Chrome browser, it can audit any website for performance, best practices, accessibility, SEO and progressive web application (PWA). Auditing your website here will probably return a lot of pointers and suggestions at first, and they are really helpful in understanding how the web works and how we can get more performance out of our websites.

PWA was really interesting, it uses Service workers to empower web applications to deliver a user experience with the reliability and performance of locally hosted websites. This is a giant leap in the world of websites; a website which behaves like a mobile/desktop application by choosing whether it needs to download a website component from your web server or whether it can use it off the local cache. On Android phones, a pop-up asks whether you want to install it or not, in case you install it, you’ll see an icon on your mobile to give a complete mobile application experience.

Audit score on Google Lighthouse (USA)

Audit results on the right: Performance 84/100, Progressive web app 100/100, Accessibility 100/100, Best practices 100/100, search engine optimization 100/100

I was able to achieve a perfect score in for accessibility, best practices, SEO and progressive web application but performance was topped at 87 and 80 on two different machines which I had. If I had invested some cash in it, there are plenty of tools which could help get a performance score of 100.

Google PageSpeed: a tool which tests a website on desktop and mobile to return a real-world performance score. Be prepared for lots of pointers at first, which all help make the website lighter, faster, better. In case of my beta website, the only Achilles heel turned out to be two Google tools. The fact that Google tag manager and Google analytics have a short browser cache expiry of 15 minutes and 2 hours respectively meant that I was penalized and it prevented a score of 100. It was ironic especially because both of these tools were made by Google, who also owned this performance website. Again, there was no budget for optimization, so I didn’t go for a paid analytics tool which could have covered this particular metric.

Google PageSpeed Score

Audit results on the left: Desktop 98/100, Mobile 96/100

GTmetrix: very similar to the other two tools discussed above in many aspects like a timeline, loading times, size etc. GTmetrix helped by breaking down the individual components on the website and how optimizing these particular assets could help achieve a perfect score. Cache times for Google Tag Manager and Analytics took away some percentage points to leave me at 98% on the performance score. The details which were really interesting were the need to specify image dimensions and how minified Javascript files for analytics could help get a perfect score. This tool lets you download the result of your website as a pretty report which you can use to analyse and improve your website.

GTmetrix score

GTmetrix scores on the bottom

Web Page Test: I first saw it on the dialog box which opens up during the lighthouse audit run. It is a web-based tool, which lets you simulate your website views from a variety of pre-set locations and devices which help deliver a complete usability and performance score. Usage of cache and compression was the thing which was unique about it along with other metrics which were covered by the tools discussed above. Third party scripts and rest APIs did cost me some percentage points here. My website resources were cached by my CDN provider and the font file there was not compressed, which cost me some points. Again, with a working budget, this would have been solved.

WebPageTest performance test score

WebPageTest.org performance test score

Can any website be optimized to get these scores?

Short answer: No. Try your favourite website with these tools.

Long answer: You don’t necessarily need to. A website is created to serve its audience; to understand and fulfil their unique needs at the cost of limited time and resources. Analytics can help understand a website’s audience, their needs, locations, technology, behaviour and time spent. All of which is invaluable in tailoring the experience for that customer.

Some of the best practices outlined in these tools will take a lot of time for very little return. Some of these would not take all that long but might make the maintenance of the website very expensive in the long run. Hence, some metrics could be achieved by investing more capital and bearing more recurring costs. It is a careful balancing act which is unique to each website, its organizational setting, underlying technology, time and budget limitations.

And while all of this is done, a new set of standards and technological advancement may bring newer benchmarks and best practices. Network speeds at different times of the day resulted in different readings as well, but this is why I didn’t follow a single tool but followed multiple tools which could help test my website from different locations on different devices. It would be interesting to see where this website will rate in the next 3 months, 6 months, in a year!!

Async – await using axios

var t= new Date; var timeStr = t.toUTCString();
function getCoffee() {
return newPromise(resolve=> {
setTimeout(() =>resolve(‘☕ mocha coffeee’), 2000); // it takes 2 seconds to make coffee
});
}
asyncfunctiongo() {
try {
// but first, coffee
const coffee = await getCoffee();
console.log(coffee); // ☕
document.getElementById(‘asyncTest’).innerHTML = coffee;
// then we grab some data over an Ajax request
constwes = await axios(‘https://api.github.com/users/wesbos’);
console.log(wes.data); // mediocre code
const footerData = await axios({ url:footerLinks, method:’GET’, responseType:’json’ });
console.log(footerData.data); // mediocre code
var totalString = ‘ ONE : ‘;
for (vari = 0; i

totalString = totalString + tagContent;
}
document.getElementById(‘sectionNormal’).innerHTML = totalString;
} catch (e) {
console.error(e);
}
}
go();
<body>
<h1>Bismillah ar Rehmaan nir Raheem</h1>
<hr />
<hr />
</body>