I choose the cheapest option which is $5 per month. They are providing a lot of combination for users to pick a suitable droplet.
# Setup SSL
I’m setup my ssl certificate using Let’s Encrypt service.
# Nginx and Brotli compression
Brotli compression – a smaller size of files streams to end users. Thus, make your website feel performance.
I choose Ubuntu as my server’s operation system(OS). Then, configure the Nginx to serve my website. Recommended to install Nginx from source or Nginx official repository instead of from the package provided by the Ubuntu. This is because I have some problem when I want to add a new compiled module to existing Nginx. (tutorial)
// Further reading
SSL is required for setup brotli compression, however, you may skip Step 1 if you had setup SSL for your website previously.
# NextJS and Material-UI
Previous SPA website is written from scratch using ReactJS and Bootstrap. Then, I rewrite it using NextJS (Static rendering and Server Side Rendering) with Material-UI as the base design system. (Source code)
Implementing git hooks automation process, whenever I push the new changes to my droplet, git hooks post-receive will checkout the new changes from master branch.
The process will be as below:
Git push to specified droplet
Checkout new changes
Stop existing pm2 process (Depend on droplet resources, if your droplet have enough resources. Then, skip this step)
Reinstall node_modules,
Rebuild NextJS app
Start/Restart pm2.
while read oldrev newrev ref
do
if [[ $ref =~ .*/master$ ]];
then
echo "Master ref received. Deploying master branch to production..."
git --work-tree={path to webroot} --git-dir={source of directory} checkout -f
else
echo "Ref $ref successfully received. Doing nothing: only the master branch may be deployed on this server."
fi
done
stop_next_app &&
cd {/path/to/webroot} &&
yarn install &&
yarn build &&
start_next_app
// When a component mounted, it will execute this lifecycle for once
componentDidMount() {
const { selectedIndex } = this.state;
this.fetchStories(storyTypes[selectedIndex].path);
}
Import the following from respectively library.
import { FlatList } from "react-native";
import { ButtonGroup, ListItem, Icon } from "react-native-elements";
render() – render the UI. Modify the render() method inside the class to the following. this.renderNews has error ? No worry will implement it next.
Take a closer look at the shouldComponentUpdate. shouldComponentUpdate determines whether a component should re-render or not.
// By default this lifecycle will return true
shouldComponentUpdate(prevProps: Props, prevState: State) {
const { isSelected } = this.props;
const { details } = this.state;
// Now, we restrict the condition to only re-render
// when the following value had changed
return details !== prevState.details || isSelected !== prevProps.isSelected;
}
Implement function for bookmark action
Next, go back to StoryList.js file. Then, implement the function for the bookmark action.
// import the NewsItem component
import NewsItem from "NewsItem";
class StoryList extends PureComponent {
...
handleOnPressBookmark = (id: number) => {
return () => {
const { bookmarks } = this.state;
const tmpBookmarks = [...bookmarks]; // clone the array
// Checking whether the selected "id" exist in the bookmarks list
if (tmpBookmarks.find((tmpBookmark: number) => tmpBookmark === id)) {
// Remove the selected "id" if it existed
const removeBookmark = tmpBookmarks.filter(
(tmpBookmark: number) => tmpBookmark !== id,
);
// update state
this.setState({
bookmarks: [...removeBookmark],
});
} else {
// otherwise, push it to the bookmarks list
tmpBookmarks.push(id);
this.setState({
bookmarks: [...tmpBookmarks],
});
}
};
};
...
}
Below is the sample. For this demo. (Forget about the SearchBar, is not included in this tutorial)
Enhance the bookmark action by using Set in ES 6
Now, let us refactor the handleOnPressBookmark() as below.
constructor() {
this.state = {
...,
bookmarks: new Set([]) // initialize to Set instead of Array
}
}
handleOnPressBookmark = (id: number) => {
return () => {
const { bookmarks } = this.state;
const tmpBookmarks = new Set(bookmarks);
// Now, the code is easier to read and understand
// And we save the system resource from looping array
// Checking whether has the "id"
if (tmpBookmarks.has(id)) {
tmpBookmarks.delete(id); // remove it, if existed in the bookmarks
} else {
tmpBookmarks.add(id); // otherwise, add into the bookmarks
}
this.setState({
bookmarks: tmpBookmarks,
});
// Below is previous version, for easier comparison
// if (tmpBookmarks.find((tmpBookmark: number) => tmpBookmark === id)) {
// const removeBookmark = tmpBookmarks.filter(
// (tmpBookmark: number) => tmpBookmark !== id,
// );
// this.setState({
// bookmarks: [...removeBookmark],
// });
// } else {
// tmpBookmarks.push(id);
// this.setState({
// bookmarks: [...tmpBookmarks],
// });
// }
};
};
Access bookmarks.size is similar to Array().length
Implement data fetching in componentDidUpdate. This is related to the onPress function in ButtonGroup. The onPress function only update selectedIndex without further action.
componentDidUpdate(prevProps: Props, prevState: State) {
const { selectedIndex } = this.state;
// Then, we can handle the action in componentDidUpdate
// Whenever a component re-render, the lifecycle will triggered
// Thus, we can handle some action here after re-render
// **Always do comparison, to prevent infinite loop
if (prevState.selectedIndex !== selectedIndex) {
this.fetchStories(storyTypes[selectedIndex].path);
}
}
Some personal experiences on React Native stack. The things that a developer should know. (Not need to know all at once, just for reference, where to go next)
Mainly in JavaScript – ES6. Here, a resource for learning ES6 feature. Since, React Native is able to expose native iOS and Andriod functionality to JavaScript. In some case, developer should know the programming language in both platform, such as Objective-C or Swift and Java or Kotlin. For example, some localize payment gateway due to the provider only release native SDK. Then, developers have to create the “bridge” to expose the function from native SDK to JavaScript. In order to implement it into React Native.
Second, TypeScript – static typing programming language. You can opt-in for using TypeScript to create React Native mobile application.
Flow
Optional library for JavaScript to static typing. Which help developer reduce run-time and compiled error. Generally help in produce a more stable and debuggable JavaScript application.
Continuous Integration and Continuous Delivery (CI/CD)
Get to know which CI/CD would help you or your project. Automated your deployment to Play Store and App Store can save tons of time from work flow. Nevercode, CircleCI or Bitrise is CI/CD platform that you can try to automated your React Native deployment. Sign up an account from Bitrise or CircleCI as both of them provided free plan with limitation for developer.
Provide update over the air without go through App Store and Play Store as long as the update don’t violate the App Store and Play Store T&C and modify the purpose of your app.
#Library
ReactJS
It’s good to know the ReactJS before start React Native. Why ? To avoid writing crappy code that will bring tech debt to the code base. At least, developers should know the lifecycle, state, props and rendering in ReactJS. Get to know how it work, definitely make your life better.
UI Library
UI library is a collection of components that is styled with pre-define themes. More or less similar to Bootstrap or Foundation for web. Some of the famous UI library is Native Base, React Native Paper (Material UI theme) , React Native Elements and etc. (Personally, I would recommend Native Base as in the library quite mature. But, be aware of some pitfall from Native Base)
#Idea
Move fast and break things.
A famous quote from Facebook. ReactJS and React Native are inherit the spirit from the quote. Both library is moving fast, break some stuffs (Early version of React Native) and introduce new tools or API. So, if you are looking for tutorial. Please look for those new tutorial instead of month(s) ago or year(s) ago tutorial. Keep yourself updated from ReactJS blog or React Native blog. (Stop using componentWillMount for newbie, it’s deprecated)
File Structure
Learn to know the size of your app or discuss with your team first. It help you have a better overview to structure your folders and files.
Get to know the idea of Closure. It’s help you understand the functional programming pattern. It do help you understand how to create a Higher order Component using Closures but for component.
A good technique for optimizing React Native application. Only load specific resource when needed.
Composition
Get yourself familiar with the idea of composition instead of inheritance. For example, it’s sort of like playing lego. Joining small pieces of lego to build something.
Conclusion
Basically, this is a list of my personal experience regarding React Native stack. It’s not limited to this list. The rest, such as how to manage environment for dev, staging or production ? How to manage configuration in build.gradle or plist.info file ? Unit testing, end to end testing.
Out of topic, Why choose React Native ? My answer is because of declarative UI.
As the code show above, we fetch the topstory news at useEffect which is when the component mounted. Then, display the result – a list of story Id in the <FlatList />.
What if we want to reuse the same stateful logic somewhere else or maybe sharing the same codebase with React Native ?
Copy paste
Custom React Hooks
Step 2 – Extracts React Hooks into custom React Hooks
Well, let’s extract current structure into a custom React Hooks for reuse purpose.
Now, create a new file called useStory.js and copy paste below code into the file.
Now, we extract the stateful logic into a custom Hooks. The naming convention of custom React Hooks should prefix with use. There is a eslint plugins to help developer linting the naming of custom React Hooks.
useEffect – fetching API request and return a function that will be execute when the component unmount. Cancel an API request or remove event listener will be done inside return function.
Access to the state ? Return the state at the end of the custom React Hooks.
Step 3 – Refactor component to use custom React Hooks
import React from "react";
import { FlatList } from "react-native";
import { Container, Content } from "native-base";
import NewsItemWithAPIUsingHooks from "../components/NewsItemWithAPIUsingHooks";
import useStory from "../hooks/useStory";
export default function DemoReactHooks() {
const topstories = useStory("topstories");
function renderStory({ item, }: { item: Object }) {
return (
<NewsItemWithAPIUsingHooks storyID={item} />
);
}
return (
<Container>
<Content>
<FlatList data={topstories.response} keyExtractor={(item, index) => `${item}-${index}`} renderItem={renderStory} />
</Content>
</Container>
);
}
Now, it’s much more cleaner than before. useStory React Hooks is able to reuse in other component even in React Native without copy paste.
Conclusion
Finally, come to an end of the series of creating reusable stateful business logic, to share codebase among web and mobile app (ReactJS and React Native).
To maximize the reusability of HoC or custom React Hooks, it’s better to keep it as simple as possible and not coupling too much third party JavaScript library.
A reusable HoC or custom React Hooks is good for Junior developer or someone who is new to a project’s codebase or team. This way can reduce the time to study and get familiar with the codebase and make them onboard as soon as possible. They can be more focus on the input and output.
Maintenance issue. Now, fixed a bug in business logic only done once instead of twice or more.
Separation of concern. Separate business logic out of the presentation view. Easier for unit testing and update UI especially when the component grow larger
Thanks for reading. Full source code can be obtain from my github repository
In my previous post, I explain about write a HoC, encourage more reuse of codebase. This post I will try to explain more example, to make a HoC more flexible (certain use case).
Given example above from my previous post. We facing an issue as following:
It’s only allow developer to fetch topstories resource from HackerNews API. (may not be a bad case, sometimes)
// latest item from HackerNews API
https://hacker-news.firebaseio.com/v0/maxitem.json?print=pretty
// Up to 500 top stories / new stories / best stories
https://hacker-news.firebaseio.com/v0/[topstories|newstories|beststories].json?print=pretty
// Up to 200 Ask / Job / Show stories
https://hacker-news.firebaseio.com/v0/[askstories|showstories|jobstories].json?print=pretty
It’s okay that if you build each API endpoint a standalone HoC (For single responsibility pattern or maybe due to business logic is vary). What if you can reuse the same HoC even for some combination too.
Below is an example, make it as dynamic as possible (Please prioritize maintaining rather than dynamic use case, as in most of the time the most dynamic function is the one hardest to maintain and debug, trade off)
Since, HoC is a JavaScript closures. We can modify it to take in and holding additional parameter – endpoint and dynamicProps.
This way a developer can passing any endpoint (Let’s limited to certain purpose or use case, otherwise it will caused the HoC hard to maintain at the end).
Then, the dynamicProps define how a developer accessing the the props. dynamicProps is defined by developer, for two purpose.
The business logic / HoC is encapsulated. Developer more focus on input and output. Less worry for handling business logic.
To prevent props collision, when it’s come to combine two or more HoC
export default function withStories(endpoint, dynamicProps) {
return (WrappedComponent) => {
return class extends React.Component {
...
render() {
return <WrappedComponent {...{ [dynamicProps]: value }} />
}
}
}
}
Combines two or more HoC
One of the way, to combine multiple HoC as below:
withHoCOne(withHoCTwo(withHoCThree(App)));
Well, it solve the combine multiple HoC issue. At the same time, it create another issue – readability. Yes, the code is hard to read.
Here, recommend some utility to help solving the issue and maintain the code readability.
Redundant props or some unused props. In ReactJS, a component is re-render when the props changed. So, if a HoC passing some redundant props and the value had changed it will caused the component to re-render. A bug that is hard to trace.
Conclusion
Wisely use of HoC is promoting the reuse of codebase. Improve maintainability and component unit testability.
Wrapped API in Higher order Component to promote reusable component and static component unit testing
Scenario
Create a component, fetching API/resources in componentDidMount. Most of the tutorial, start this way. This is the easier way for anyone to learn fetching API/resources in ReactJS/React Native. I don’t against this pattern. But, things go complicated in real world business. Fetching multiple API or reuse the same business logic (stateful business logic).
Copy paste might solve your problem and create duplicated code or even worse the codebase will grow very fast. What if you can done the job with a function instead of copy paste ? This way you can separate the business logic and presentation component, making component smaller and modular. It will be a good investment in long terms (reduce tech debt).
Wrapped API/resources fetching or business logic in Higher order Component promote the reusable of presentation component and business logic.
** A plain Higher order Component without too much dependencies allow you to share the same code with ReactJS for web or vice versa.
*From here onward, will calling HackerNews API for demo purpose*
Let’s start with fetching topstories from HackerNews API – return a list of story ID. Then, fetching another API for particular story details.
// list of story ids
https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty
// details of story
https://hacker-news.firebaseio.com/v0/item/121003.json?print=pretty
First, let create the first Higher order Component (HoC), for topstories from HackerNews API.
In Higher order Component, component was parameterized – WrappedComponent. In above example, the HoC can now be reuse to any component that need to access the topstories resources.
The withTopStories will fetching the topstories resources from HackerNews API and set to the state – stories. Later on, passing the resources as a props to the parameterized component – WrappedComponent.
Accessing the injected props
Now, we want to access the injected props. Maybe a <FlatList />
import React, { Component } from "react";
import { FlatList, Text } from "react-native";
import withTopStories from "path/to/withTopStories";
class App extends Component {
renderStories({ item, index }) {
return <Text>{item}</Text>
}
render() {
const { stories } = this.props;
return <FlatList
data={stories}
renderItem={this.renderStories}
keyExtractor={(item, index) => `${item}-${index}`}
/>
}
}
export default withTopStories(App);
Then, we will render a list of number which is the story’s ID from HackerNews API. In order to get the details, we need the ID to fetch another API.
Yet another HoC for another endpoint
Then, we create another HoC for fetching the details of story by the ID.
Now, we need a component to display the details. Let’s create one. This time we won’t wrapped it directly, instead we will create a static version. This allow us easy to mock the data and unit testing the component.
import React from "react";
import { Text } from "react-native"
export default function Story(props) {
const { details, ...rest } = props;
return <Text {...rest}>{details.title}</Text>
}
/**
* Version 2.0
*/
import React, { Component } from "react";
import { FlatList } from "react-native";
import withTopStories from "path/to/withTopStories";
import withStoryDetails from "path/to/withStoryDetails";
import Story from "path/to/Story"; // the component we create above
const WrappedStory = withStoryDetails(props => {
const { storyID, ...rest } = props;
return <Story storyID={storyID} {...rest} />
});
class App extends Component {
renderStories({ item, index }) {
// replace the below component
return <WrappedStory storyID={item} />
}
render() {
const { stories } = this.props;
return <FlatList
data={stories}
renderItem={this.renderStories}
keyExtractor={(item, index) => `${item}-${index}`}
/>
}
}
export default withTopStories(App);
Closing
Now, both React Native and ReactJS can share the HoC. Use it on mobile or web. Wrapped it with any presentation component without duplicate code. Easier to unit testing static component.
Starting React Native 0.60 above modules will totally remove from React Native Core. In order to utilize specific module you need to install it as separate library from react-native-community.
Why you shouldn’t to React Native 0.60 immediately ?
Bug fixes and new features that introduce in React Native 0.60 is great. But, you may want to take consideration before upgrading.
The main issue is that React Native 0.60 migrate to AndroidX where most of the library has not ready yet for this changes. So, in order to upgrade to React Native 0.60. You may need to ensure all the third-party plugins/library in your application is compatible with AndroidX. Although, soon they will migrate to support AndroidX too. But, not at the moment.
Upgrade Helper
Upgrade helper – upgrade made easy. A new web tools that can help developer upgrading their react native easily. As it is comparing the different of two different react native version and show the difference side by side in web browser.
17 June 2019 – Dear Google release new update for Google Play service and Firebase. Out of sudden, react native application failed at compile time and keep complaining the following message.
Manifest merger failed : Attribute [email protected] value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:5:5-19:19 to override.
But, why ?
Why is it related to Google releasing new update for Google Play service and Firebase ?
Here is why. The update will required you to update your app to use Jetpack (AndroidX). Hence, you need to migrate your app to AndroidX, if you haven’t migrate yet. Android official website do provide the guide to do so – Migrating to AndroidX.
Adding the following to your gradle.properties file in the root project folder. For react-native project – rootProject/android/gradle.properties
React Native plan to support AndroidX in the next release RN 0.60. React Native June Update. So, most likely that third-party React Native library will follow afterward.
If your react native app facing any issue as describe above, I suggest a few to solve your problem.
#1 If your app use any Google API service
In your build.gradle,
dependencies {
// Please do this
implementation "com.google.android.gms:play-services-gcm:16.1.0"
// Not this, as this line will always fetching the latest version
// implementation "com.google.android.gms:play-services-gcm:+"
}
Locked the version of Google API service, instead to taking the latest version can save you from the error. As long as your version is not the one in latest version, then you are good to go.
#2 Updating third-party React Native library
So far, what I know is that react-native-device-info is releasing a patch to fixes this issue. Maybe there is other library affected as well, that you may need to find it out.
#3 Migrating to AndroidX
But, this is not a reliable way for React Native, especially if your app depend on a huge amount of third-party library.
For more details, please refer to this github issue.
Coursera, edX or Udemy offered a wide range of courses. While, Udacity offered courses that are mostly related to technology.
Why taking programming class through MOOC is better than conventional university ?
Offered updated technology in the industry.
Courses from local colleges or universities often outdated or not practical
Offered both free and paid course, paid for the course only if you want a certificate from the course (Where the cost may vary, but cheaper than local colleges or universities)
Get practical advise/skills from industry expert.
Anyone have the chances to communicate or share your idea with others around the world