React Native 0.59

Why you need React Native 0.59

tldr

  • React Hooks in React Native
  • New JavaScriptCore
  • Support android 64-bit apk (Google Play Store Requirement)
  • Inline requires (Faster app launch)
  • And Breaking Changes !!! (Just Kidding  😂)

#1 React Hooks

React hooks make us having more code to be share among React Native app especially when involving state. From my experience, there are a lot of logic that involves state, we can share among the component instead of create a new one… (Flutter did this, due to their designation. Their widget allow them to share state that contain certain logic with others widget)


#2 New JavaScriptCore (Android)

Separate out the JavaScriptCore out of Android instead of binding together. This allow developer to upgrade the JavaScriptCore version for android or built their JavaScript VM. Performance improving and size is increasing too… 😂


#3 Support android 64-bit apk

According to this post, Android developers are require to submit 64-bit apk to Google Play starting 1st August 2019. So, this upgrade is important for most of the React Native app.


#4 Inline Require

Yet another helpful resource, for improving React Native’s performance. Inline require + RAM bundling greatly improving React Native performance.


#5 Breaking Changes

As usual, React Native 0.59 did some breaking changes to the core component as well. For more details information, may refer to their blog post. In RN 0.59, they separated some core component, such as React Natice CLI, NetInfo and AsyncStorage. They took it out and host under react-native-community

Upgrade React Native

Manually upgrade using rn-diff-purge. So far, this is the safer way to upgrade react-native. react-native-git-upgrade no longer maintained and I try it to upgrade React Native from 0.57 to 0.59.1 but it failed.

If you are using React Native version below 0.49. Then, it is possible to use react-native-git-upgrade. Upgrade React Native version to 0.57 and then manually upgrade to 0.59.

npm install -g react-native-git-upgrade

react-native-git-upgrade
// or
react-native-git-upgrade version

This method is not guarantee to work for all React Native upgrade.

SnapEffect

How to create snap effect on FlatList

Introduction

A simple demonstration for FlatList snap on scroll effect.

How ?

By adding 4 props. That you can create a snap effect on FlatList.

They are snapTiAlignment, snapToInterval, decelerationRate and pagingEnabled.

Follow the links for more documentation about the props from official react-native.

<FlatList
    data={this.VEGETABLES}
    renderItem={this._renderItem}
    keyExtractor={this._keyExtractor}
    horizontal={true}
    snapToAlignment={"start"}
    snapToInterval={this.IMAGE_WIDTH + 10}
    decelerationRate={"fast"}
    pagingEnabled
/>

Example

https://youtu.be/EHfwHxWJB7U

Thanks for reading. 😀

Source

For those interesting for the complete source is available on my github repo.

Feel free clone it and checkout the specific branch to try it out. 😀

git clone https://github.com/yikkok-yong/sample.git
git checkout sidestory/flatlist-snap-effect

Plugins in VS Code

Plugins in VS Code

The plugins that I use in VS Code:

  • Speed up development
  • Reduce run-time error (linting)
  • Auto-formatting

Editorconfig 😍

Using space or tabs ? Indentation should 2 instead of 4 ? LF, CR or CRLF ? standard charset ? 

Different developers have their prefer coding styles. Different editor will saving the file in slightly different format according to your platform (Windows, Mac or Linux)

Therefore, editorconfig is here to solve the problem. To maintain consistent coding styles for different file type across multiple platform or developers. 

Prettier

To format JSX code in React and React Native. Eslint to linting React and React Native. This is a popular plugin among web developer to format HTML code.

Flow-language-support 😍

Flow – a JavaScript type checker released by Facebook. Due to the nature of JavaScript – non-strict type language, it make developer life harder when coming to debug JavaScript. 

With the help of Flow , one can greatly reduce the time when debugging JavaScript. Depend on plugin implementation, Flow do help give warning for undefined, null or undeclared variables in JavaScript. 

One of the downside of Flow is very resources consuming (CPU / RAM). So, one might need to consider it only if you have enough resources to run it.

** Latest React Native is migrating from PropTypes to Flow.

React Native Tools

Code hinting for React Native and debugging React Native app integrate with the native debugging function come with VS Code – allow you to set breakpoint or other debugging action. 

Flutter and Dart Code

I don’t need to repeat the introduction here, I bet that all flutter developers know about these plugins, as it is included in Flutter documentation and very helpful to flutter development. 

Docker

To start, stop, debug, configure, syntax highlight, linting your dockerfile or docker-compose. 

Path Intellisense 😍

Module not found ? No such file or directory error ? No problem, this plugin come to rescue you.

No more hassle in looking for the path to specific file. This plugin provided suggestion/autocomplete to file and directory. Plugin author provide some configuration for this plugin too. Feel free to utilize it to maximize your productivity.

Regex Previewer

There is a lot of free tools/website provide help for regex. What if there is a plugin in your editor ? Now, you can validate your regex directly without exist editor. 

REST Client

A plugin for you to test your RESTful API. A great plugin to test RESTful API without leaving editor. 

Cobalt2-theme 😍

Last but not least, this is a theme plugin. I like the cobalt blue color when I  start using Ubuntu. Other than this, there is other theme plugins as well, such as Atom One Dark theme. 

Conclusion

There are tons of the plugins in VS Code marketplace. Feel free to utilize them to solve your problem. So, you can have a sweet dream instead of nightmare at night. 😜

Thanks for reading. Feel free sharing your recommended plugins to me. 

Ethereum and Smart Contract

Ethereum and smart contract

Don’t be pushed around by the fears in your mind. Be led by the dreams in your heart.

Roy T. Bennett

One year ago, I got to know ethereum and smart contract. This post is serve as a documentation and sharing to those who interested develop smart contract in ethereum.  

Ethereum

Ethereum – A decentralized platform where you deploy and execute smart contract.

Download and install ethereum’s protocol – geth.
This is the entry point to ethereum’s main network, test network or private network. By connecting to any network, you’ll join the network as a node.

Smart Contract

A piece of source code that people assume it will replace the middle-man, such as lawyer or agent in the future.

Below is some tools that you need before start developing smart contract:

#1 Ethereum wallet

Download Ethereum wallet from Github repo

  • Ethereum wallet
  • Mist Browser – Browse Dapps or function as Ethereum wallet
  • MetaMask – a browser extension to access Ethereum mainnet or testnet

#2 Programming language

Solidity 

  • A new object-oriented programming language, for creating smart contract in Ethereum
  • Similar to C++ and python (Personal thought, I don’t feel it is similar to JavaScript, despite their website stated)
  • Partial supported fixed point number (Decimal point)
  • VS Code – solidity extension

#3 Framework

Truffle framework's logo
Image via https://truffleframework.com

Truffle

  • Compile, deploy and debug your smart contract
  • Ganache – Provided testing environment for your smart contract (formerly called TestRPC)
  • Drizzle – develop dapp (decentralized application)

#4 Testing smart contract

Using Mocha or any other JavaScript test runner. That can greatly simplify developer work flow and make testing automated.

  • Deploying smart contract depend on mining process, automated testing script can reduce the time waiting for deploy
  • Once deployed, smart contract will stay forever in the network, therefore, test as much as possible before deploy smart contract.

#5 Upgradable smart contract

Splitting smart contract into business logic and data smart contract. Then, developer can upgrade business logic smart contract without touching data part. 

Pro:
  • Easier to tackle smart contract bug in production environment
Con:
  • Higher cost in term of deploying smart contract

#6 Library

OpenZeppelin –  smart contract library that you can use to develop secure smart contract. This library has prepared a lot smart contracts for various use case. Developer just need to include and extends the smart contract with or without modification.

Thanks for reading. Have a nice day. 😀

Component Optimization

Component Optimization

Breaking a program into smaller modules.

I do believe most of the computer science students heard the quote above. This post is talk about component optimization in React/React Native.

Introduction

One may ask, since we can done all job in one component, why do we need to break it into several components ? 

For: 

  • Better maintainability 😁
  • Reusable (although it is seldom being achieved) 🤔
  • Performance 😍

In this post I will demonstrate a simple clock that update every second. 

type Props = {};

type State = {
  timer: string
};
export default class Clock extends Component<Props, State> {
  countDownIntervalID: any; // To store the value return setInterval

  ONE_SECOND: number = 1000; // 1000 milliseconds
  BUTTON_TEXT_STOP: string = "Stop";
  BUTTON_TEXT_START: string = "Start";
  TIME_FORMAT: string = "hh:mm:ss";

  constructor(props: any) {
    super(props);

    this.state = {
      timer: moment().format(this.TIME_FORMAT)
    };
  }
}

Initial state of this screen. Currently, this is how I manage those values in my component. Declare as global variables to the class. For reuse purpose, if one never been use in another place, it is better declare as local variable.

#1 – Utilize React component lifecycle

shouldComponentUpdate(nextProps: any, nextState: any) {
  return this.state.timer !== nextState.timer;
}

componentDidMount() {
  this.countDownIntervalID = setInterval(this._countDown, this.ONE_SECOND);
}

componentWillUnmount() {
  clearInterval(this.countDownIntervalID);
}

shouldComponentUpdate , componentDidMount , componentWillUnmount are React component lifecycle. 

#2 – Functions

// Update state.timer
_countDown = () => {
  this.setState({
    timer: moment().format(this.TIME_FORMAT)
  });
};

// Stop the interval
_onPressStopHandle = () => {
  clearInterval(this.countDownIntervalID);
};

// Start/Restart the interval
_onPressStartHandle = () => {
  this.countDownIntervalID = setInterval(this._countDown, this.ONE_SECOND);
};

#3 – Render

render() {
  return (
    <View style={style.timerContainer}>
      <Text style={style.timerText}>{this.state.timer}</Text>
      <View style={style.buttonContainer}>
        <Button onPress={this._onPressStartHandle} rounded success>
          <Text>{this.BUTTON_TEXT_START}</Text>
        </Button>

        <Button onPress={this._onPressStopHandle} rounded danger>
          <Text>{this.BUTTON_TEXT_STOP}</Text>
        </Button>
      </View>
    </View>
  );
}

Here is the render() function that rendering the view. 

So, what if this screen growth larger ?

There is possible that you want to add other stuff into this screen – some texts, buttons or features. And those are needed but not necessary to re-render the view every second. It is a waste of resources. 

So, break the timer into a standalone component.

  • To minimize the re-rendering action
  • Reusable component
  • Plug and play with other components.

Just some simple sharing and thanks for reading. 😊

Remove console using babelJS

Remove console.* in JavaScript with babelJS

Prerequisite

  • Project configured with babelJS (Work out of the box in React/React Native)

Installation

Terminal screencast from asciinema
npm install babel-plugin-transform-remove-console --save-dev

Configuration

Create a .babelrc file in your project root folder, below is an example .babelrc for React-Native project.

{
  "presets": [
    "react-native"
  ],
  "env": {
    "production": {
      "plugins": [
        "transform-remove-console"
      ]
    }
  }
}
  • Presets (Preset plugins for particular platform or version, eg: react-native, react-app, env or more)

Console.* is useful in debug. Why remove it ?

We shall removed the console.* in our production released to prevent any confidential data leaked that may abused by malicious users.

There is another reason caused by console.*performance issues in JavaScript app.

Therefore, I believed the plugin is a helpful tool, that help us get rid of console.* when released into production.

React Native CLI

React Native – Part 2 🐹

# 2 react-native-cli

Suitable

  • For those who want to
    • involve native source code, either third-party or self-customized
    • integrate React Native into existing app
  • For those who are experience in React Native

Prerequisite

Other than NodeJS and NPM.
We need these to build native source code to run on specific platform.
XCode to build iOS app, Android Studio to build Android app.

  • Android Studio (Android development)
  • XCode (iOS development)
// Specify the component you want to register, 
// App is just an example.
// This line is not required, if using Expo
AppRegistry.registerComponent("App", () => App);

This is another prerequisite in React Native project, It is automatically generated, if the project is initialized by react-native-cli. If we are ejecting from create-react-native-app, then we need to add this to our entry file, eg: index.js.

For more details regarding installation can refer here.

React Native – Part 1 (create-react-native-app)

React Native - Create React Native App

React Native – Part 1 🐹

This post is in bilingual (Chinese and English). 
This is not a tutorial post for how to install React Native.
But, a simple comparing which method you should go for install React Native for newcomer. 

此文并非教学文,只是想让新手们了解,哪一种方式更适合新手去摸索React Native。

Prerequisite

  • NodeJS and NPM/Yarn
    • NPM will be installed together with NodeJS
    • Yarn or NPM either one will do
    • Go for LTS version, if you not which version to pick

必备
NodeJS与NPM,NodeJS中文网

npm install -g create-react-native-app
npm install -g react-native-cli

Both commands above, will install the package to our system, so that we can execute it within the system.

以上的指令,会将组件安装于系统范围,而非项目范围。让开发人员可以在系统范围内,执行指令。

** Windows user might need this package windows-build-tools

Methods to install React Native

# 1 create-react-native-app

Using create-react-native-app to initialize a project

Suitable

  • For those who want to
    • learn the basic before go deeper
    • create a cross-platform app without any customized native source code
    • create a prototype
    • experiment purpose
create-react-native-app [project-name]

create-react-native-app provided the most simplest solution to try out the react-native without deaaling with XCode or Android Studio (unless those who want try it on simulator).

create-react-native-app 是当前比较方便和省时的方式。因为这个方式提供手机应用Expo。让人们可以在实体手机上做测试。免去了设置 XCode和Android Studio. 参考以下的链接。

Example

  • The entry file is App.js. 
  • .gitignore is autogenerated with pre-fill 

Test it on your device – using Expo !

Provided Expo SDK to develop React Native.

Downside

We can’t link/bridge any customized native code.
(Unless we eject our project) 
So, for those who just want to try out the react native for fun.
create-react-native-app is better solution.

这个方式的坏处是,不能运用 IOS和Android 的定制原代码。
不过,就纯粹接触,create-react-native-app可说是不二选择。

React Native – Part 2 (react-native-cli)