Skip to content

Instantly share code, notes, and snippets.

@amandeepmittal
Created February 18, 2019 12:57
Show Gist options
  • Save amandeepmittal/3c5c81a26ff0fa1b9ff8515daf9d226f to your computer and use it in GitHub Desktop.
Save amandeepmittal/3c5c81a26ff0fa1b9ff8515daf9d226f to your computer and use it in GitHub Desktop.

Building a React Native App with React Hooks

React 16.8.x welcomed the dawn of Hooks. This new addition is both a concept and pragmatic approach that helps you use state in a React component (and some other features) without writing a class. React as a front-end library is becoming powerful and more developer friendly at the same to use due to such updates. I think it is an important part of being a developer and using something like React in our work/day-job/side-hustle projects by keeping up to date with these new features.

Following the footsteps of ReactJS, React Native community recently announced that they will be adding support for hooks shortly in the upcoming version 0.59.x. I have been waiting for them to officially make this announcement before I publish this tutorial, only to spike up your interest in Hooks.

In this tutorial, I will walk you through the steps on using Hooks in a React Native application. Even before the initial release, if you are curious and want to test this new feature out, you can follow the steps below in setting up. Moreover, if you have never worked with React Hooks, and have been longing to do so, this is the right time and this tutorial, the right opportunity for you to expand your horizons.

Table of Contents:

  • Getting Started with Hooks and React Native (setup)
  • What are Hooks?
  • Implementing Hooks in React Native
  • Building a Todo List App with Hooks
  • What is Flexbox?
  • Adding Hooks to the App
  • Rendering the List
  • Completing and Deleting an Item
  • Conclusion

Getting Started

As per the current date, hooks in React Native are still in release candidate (RC) mode. It is a build released internally to check if any critical problems have gone undetected into the code during the previous development period. Do note here that, a release candidate version of a framework is not to be used in production since it is not stable and only to be used for testing purposes.

That said, to you use React Native's RC 0.59.0-rc.1 all you to run the below command from your terminal.

https://gist.github.com/eee23989e2916f4472c53c0cbd9950f2

Using this command, a new project folder will be generated, traverse inside it and you will be welcome by a slightly different file system (new file that you might not have seen before is metro.config.js, which you can ignore it for now).

(ss1)

Also note that RNHooksTODOAPP is the project and directory name, so in its place, you can enter anything. For more information on the current release candidate of React Native, you can visit their Github project.

https://github.com/facebook/react-native/releases

To run the mobile application in an iOS/Android simulator you can run the same old CLI commands like react-native run-ios or run-android.

What are Hooks?

Hooks in React have been available since the version 16.7.0-alpha. They are functions that allow you to use React state and a component's lifecycle methods in a functional component. Hooks do not work with classes. If you are familiar with React, you know that the functional component has been called as a functional stateless component. Not any more.

Since previously, only a class component allowed you to have a local state. Using Hooks, you do not have to refactor a class component when using React or React Native into a functional component only because you want to introduce local state or lifecycle methods in that component. In other words, Hooks allow us to write apps in React with function components.

React provides a few built-in Hooks like useState. You can also create your own Hooks to re-use the stateful behavior between different components.

Implementing Hooks in React Native

In the example below, let us take a look at how you will manage local state of a component by using Hooks. Open up App.js file and paste this code.

https://gist.github.com/f6855c93faa6d1880c73c1f09200eaee

We will start by writing a basic old-fashioned counter example to understand the concept of using Hooks. In the above code snippet, you are starting by importing the usual along with useState from react library. This built-in hook allows you to add a local state to functional components. Notice that here export default function App(), instead of traditionally writing a class component we are defining a normal function.

This App function has state in the form of const [count, setCount] = useState(0). React preserves this state between all the re-rendering happening. useState here returns a pair of values. The first one being the count which is the current value and the second one is a function that lets you update the current value. You can call setCount function from an event handler or from somewhere else. It is similar to this.setState in a class component. In above, we are using the function inside the button component. setCount(count + 1)

useState(0) hook also takes a single argument that represents the initial state. We are defining the initial state as 0. This is the value from which our counter will start.

To see this in action, open two terminal windows after traversing inside the project directory.

https://gist.github.com/8ec24f0013a38cdc690e2774a6083aab

Once the build files are created, the simulator will show you a similar result like below.

(ss2)

If you play around a bit and hit the button Click me, you will see the counter's value being increased.

(ss3)

As you know by now, that the App component is nothing but a function that has state. You can even refactor it like below by introducing another function to handle Button click event and it will still work.

https://gist.github.com/23dacdb1f9dcb1b9052d3bcbc6535502

Building a Todo List app with Hooks

In this section, you are going to build a Todo List application using React Native framework and Hooks. I personally love building Todo list applications when getting hands-on experience over a new programming concept or approach.

We have already created a new project in the last section when we learned about Hooks. Let us continue from there. Open up App.js and modify it with the following code.

https://gist.github.com/9b956e579ea0a67a81282b52145d8564

We need a text input field to add items to our list. For that, TextInput is imported from react-native. For demonstration purposes, I am keeping styles simple, especially the background color. If you want to make the UI look good, go ahead. In the above code, there is a header called Todo List which has corresponding header styles defined using StyleSheet.create object. Also, take notice of the View which uses justifyContent with a value of flex-start.

Creating a UI in a React Native app heavily depends on styling with flexbox. Even if you decide to use a third party library kit such as nativebase or react-native-elements, their styling is based on flexbox too.

The flexbox layout starts by creating a flex container with an element of display:flex. If you are using flexbox for the web you will have to define this display property. In react native, it is automatically defined for you. The flex container can have its own children across two axes. The main axis and cross axis. They both are perpendicular to each other.

These axes can be changed as a result of property flexDirection. In the web, by default it is a row. In React Native, by default it is a column.

(ss11)

To align an element along the horizontal axis or the cross axis in React Native you have to specify in the StyleSheet object with the property of flexDirection: 'row'. We have done the same in the above code for the View that contains TextInput field.

Flexbox is an algorithm that is designed to provide a consistent layout on different screen sizes. You will normally use a combination of flexDirection, alignItems, and justifyContent to achieve the right layout. Adding justifyContent to a component's style determines the distribution of children elements along the main axis. alignItems determine the distribution of children elements along the cross axis.

Back to our app. Right now, if you run it in a simulator, it will look like below.

(ss10)

Let us add an icon to represent a button to add items to the todo list. Go to the terminal window right now and install react-native-vector-icons.

https://gist.github.com/a68618a646cee57f8035e1ae034a1938

Now go back to App.js file. We have already imported TouchableOpacity from react-native core. Now let us import the Icon from react-native-vector-icons.

https://gist.github.com/1f4e57fad50025965c0ad29a1c8af2c6

Next step is to add the Icon element inside TouchableOpacity next to the TextInput. This means the plus to add an item to the list must be on the same line or axis as the text input field. TouchableOpacity makes the icon clickable and can have an event listener function (which we will add later) to run the business logic for adding an item to the list.

https://gist.github.com/3c8d805665c1e70f61038fed49b1bed4

Now if you go back to the simulator you will have the following screen.

(ss12)

Adding Hooks to the App

In this section, you are going to add a local state to the component using Hooks. We will start by initializing the local state for the App component with the new hooks syntax. For that, you have to require useState from react core. Also, note that the initial state passed below is passed as an argument to the useState() function.

https://gist.github.com/79460168f2b85c73423fce31d9632e0e

The first value is the value of TextInput and it is initially passed as an empty string. In the next line, todos are declared as an empty array that will later contain multiple values. The setValue is responsible for changing the value of value on TextInput and then initializing the empty value when the value from the state is assigned as an item to todos array. setTodos is responsible for updating the state.

The addTodo function we define is a handler function that will check if the TextInput field is not empty and the user clicks the plus icon, it will add the value from state to the todos and generate a unique key at the same time to retrieve each todo item record from todos array to display as a list. The initial value for checked is false since no todo item can be marked as completed by default, that is when adding it to the list.

Here is the complete code for App.js after adding state through Hooks.

https://gist.github.com/bfcb3c2e91aad8f24c40dc82abc69ed9

Rendering the List

You are going to create a new component that will be responsible for displaying each task that a user adds. Create a new file called TodoList.js and add the following code to the file.

https://gist.github.com/56aedbaf3117ef55aeed0d1c044895f7

Now let us import this component in App.js to render todo items when we add them by clicking the plus sign button. Also you are now required to import ScrollView in App component from react native core.

https://gist.github.com/3285b1ec02c77f16618aa670980e09d3

The ScrollView is a component that renders all its child at once. A good case to use when you are not rendering a large amount of data or data coming from a third party API. Now, enter a new task (like below) and try adding it to the todo list.

(ss13)

Completing and Deleting an Item

This is the last section to complete our application. We need two handler functions to implement functionalities of checking a todo list item mark and deleting a todo list item.

Define two functions like below after addTodo.

https://gist.github.com/158ff3cb67bd5acf2994d102032bafc5

The first function checkTodo uses map function to traverse the complete todos array, and then check only that item that has been toggled by the user using its icon on the mobile app by matching its key (look at the addTodo function, we defined a key when adding an item to the todo list). The deleteTodo function uses filter to remove an item from the list.

To make it work, we need to pass both of these functions to TodoList component.

https://gist.github.com/6bbe0c0621f750ec8df1e3d26046c2c7

Now open, TodoList.js and these new props.

https://gist.github.com/4090104052e9fafcb06155e739ceaf9a

Now run the app and see it in action.

(ss14)

Conclusion

This completes our tutorial. I hope this tutorial helps you understand the basics of React Hooks and then implement them with your favorite mobile app development framework, React Native. By the time you are read this walkthrough, I am sure Hooks in React Native are not going to be just a release candidate. Also, in the next release of React Native, quite a few beneficial changes are coming, so keep yourself curious about it. You can extend this application by adding AsyncStorage or a cloud database provider and making this application real time. Also, do not forget to enhance the UI.

To read more about React Hooks check out the official Overview page here.

The complete code for this tutorial is available in the Github repository below.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment