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