~ 2 min read

Experiences gained by building addressBook project


  1. When I want to get a private variable from app, instead of passing that variable directly into app’s API, I should create a method returning that variable’s current value. Otherwise, that API’s property will always get the same value (the value when app’s API is initialized) but not the reference to that private variable.
    const API = (function() {
        let abc = false;
        // I will change abc's value by somehow...
        // Wrong way: API.getAbcValue() will always return false
        return {
            getAbcValue: abc
        };
        // Right way: this will get the current value of abc at the time I call API.getAbcValue()
        return {
            getAbcValue: () => abc
        };
    }());
  2. Pattern for updating a state in a React class component when you must modify the state before notifying React that the state has changed using this.setState():
    handlerAddCheckedItem(itemId) {
        const itemIndex = this.state.checkedItems.indexOf(itemId);
        if (itemIndex >= 0) {
            this.state.checkedItems.splice(itemIndex, 1);
        } else {
            this.state.checkedItems.push(itemId);
        }
        this.setState(prevState => ({ checkedItems: prevState.checkedItems }));
    }
    hoặc:
    handlerAddCheckedItem(itemId) {
        this.setState(prevState => {
            const itemIndex = prevState.checkedItems.indexOf(itemId);
            if (itemIndex >= 0) {
                prevState.checkedItems.splice(itemIndex, 1);
            } else {
                prevState.checkedItems.push(itemId);
            }
            return { checkedItems: prevState.checkedItems };
        });
    }
  3. Always keep components small, following the golden rule: Single Responsibility Principle
  4. Reorganize CSS using BEM because the size of the bundle.js file is too large (~250KB after minification)
  5. Using Redux does not bring more advantages but makes the size of bundle.js even larger.

Headshot of Nam Le

Hi, I'm Nam Le. I'm a software engineer based in HCM city, Vietnam. You can follow me on Twitter, see some of my work on GitHub, or connect with me on LinkedIn.