React Hooks Basics — Building a React Native App with React Hooks

Published on Apr 19, 2019

17 min read

REACT-NATIVE

cover_image

Originally published at Crowdbotics

React 16.8 welcomed the dawn of Hooks. This new addition is both a new concept and pragmatic approach that helps you use state and lifecycle methods behavior in functional React components, that is, without writing a class. The intention to implement this new feature in React ecosystem is to benefit all the community.

Whether you are a developer with a front-end role or write mobile apps using React Native, chances are that you are going to come across Hooks often enough in your working environment. Of course, you do not have to use them. You can still write class components, they are not going anywhere yet. However, I personally like to 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. 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 by building a small demo app and understand the most common Hooks in detail before that. Moreover, I am going to briefly introduce you to the concept of flexbox and how is it significantly different in React Native than the web.

Tldr;

🔗
  • Requirements
  • Setting up Crowdbotics Project
  • Setup a React Native app
  • What are Hooks?
  • Implementing Hooks in react native
  • Building a Todo List App
  • What is flexbox?
  • Adding Hooks to the Todo List App
  • Rendering the list
  • Completing and Deleting an Item
  • Conclusion

Requirements

🔗

In order to follow this tutorial, you are required to have the following installed on your dev machine:

  • NodeJS above 8.x.x installed on your local machine
  • Know, how to run simple npm commands
  • JavaScript/ES6 basics
  • watchman the file watcher installed
  • react-native-cli installed through npm

For a complete walkthrough on how you can set up a development environment for React Native, you can go through official documentation here.

Setting up a Crowdbotics Project

🔗

In this section, you will be setting up a Crowdbotics project that has React Native pre-defined template with stable and latest dependencies for you to leverage. However, at the time of writing this tutorial, the template does not use React Native version 0.59. So instead of going into too much hassle about upgrading this React Native app, I will be walking you through creating a new React Native project in the next section.

To follow along, setting up a new project using Crowdbotics app builder service is easy. Visit app.crowdbotics.com dashboard. Once you are logged in, choose Create a new application.

On Create an Application page, choose React Native template under Mobile App. Lastly, choose the name of your template at the bottom of this page and then click the button Create by app! After a few moments, your Crowdbotics project will be created. Upon creation, it will redirect you to the app dashboard, where you can see a link to GitHub, Heroku, and Slack. Once your project is created, you will get an invitation from Crowdbotics to download your project or clone the repository from Github either on them email you logged in or as a notification if you chose Github authentication.

Setup a React Native App

🔗

Once you installed `react-native-cli` you can begin by generating a React Native project. Run the below command to initialize a new React Native project. Also, note that you can name your React Native app anything.

react-native init RNHooksTODOAPP

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

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.

facebook/react-native

_A framework for building native apps with React. Contribute to facebook/react-native development by creating an account…_github.com

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 and useEffect. 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 the local state of a component by using Hooks. Open up App.js file and paste this code.

1import React, { useState } from 'react';
2import { StyleSheet, Text, View, Button } from 'react-native';
3
4export default function App() {
5 const [count, setCount] = useState(0);
6
7 return (
8 <View style={styles.container}>
9 <Text>You clicked {count} times.</Text>
10 <Button
11 onPress={() => setCount(count + 1)}
12 title="Click me"
13 color="red"
14 accessibilityLabel="Click this button to increase count"
15 />
16 </View>
17 );
18}
19
20const styles = StyleSheet.create({
21 container: {
22 flex: 1,
23 justifyContent: 'center',
24 alignItems: 'center',
25 backgroundColor: '#F5FCFF'
26 },
27 welcome: {
28 fontSize: 20,
29 textAlign: 'center',
30 margin: 10
31 },
32 instructions: {
33 textAlign: 'center',
34 color: '#333333',
35 marginBottom: 5
36 }
37});

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 we are writing a functional component: 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.

# first terminal window, run
npm start
# second window, run
react-native run-ios

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

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

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.

1export default function App() {
2 const [count, setCount] = useState(0);
3
4 function buttonClickHandler() {
5 setCount(count + 1);
6 }
7
8 return (
9 <View style={styles.container}>
10 <Text>You clicked {count} times.</Text>
11 <Button
12 onPress={buttonClickHandler}
13 title="Click me"
14 color="red"
15 accessibilityLabel="Click this button to increase count"
16 />
17 </View>
18 );
19}

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.

1import React from 'react';
2import {
3 StyleSheet,
4 Text,
5 View,
6 TouchableOpacity,
7 TextInput
8} from 'react-native';
9
10export default function App() {
11 return (
12 <View style={styles.container}>
13 <Text style={styles.header}>Todo List</Text>
14 <View style={styles.textInputContainer}>
15 <TextInput
16 style={styles.textInput}
17 multiline={true}
18 placeholder="What do you want to do today?"
19 placeholderTextColor="#abbabb"
20 />
21 </View>
22 </View>
23 );
24}
25
26const styles = StyleSheet.create({
27 container: {
28 flex: 1,
29 justifyContent: 'flex-start',
30 alignItems: 'center',
31 backgroundColor: '#F5FCFF'
32 },
33 header: {
34 marginTop: '15%',
35 fontSize: 20,
36 color: 'red',
37 paddingBottom: 10
38 },
39 textInputContainer: {
40 flexDirection: 'row',
41 alignItems: 'baseline',
42 borderColor: 'black',
43 borderBottomWidth: 1,
44 paddingRight: 10,
45 paddingBottom: 10
46 },
47 textInput: {
48 flex: 1,
49 height: 20,
50 fontSize: 18,
51 fontWeight: 'bold',
52 color: 'black',
53 paddingLeft: 10,
54 minHeight: '3%'
55 }
56});

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.

What is flexbox?

🔗

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.

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.

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.

npm install -S react-native-vector-icons
# Also link it
react-native link react-native-vector-icons

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

1import {
2 StyleSheet,
3 Text,
4 View,
5 TouchableOpacity,
6 TextInput
7} from 'react-native';
8
9import Icon from 'react-native-vector-icons/Feather';

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.

1<View style={styles.textInputContainer}>
2 <TextInput
3 style={styles.textInput}
4 multiline={true}
5 placeholder="What do you want to do today?"
6 placeholderTextColor="#abbabb"
7 />
8 <TouchableOpacity>
9 <Icon name="plus" size={30} color="blue" style={{ marginLeft: 15 }} />
10 </TouchableOpacity>
11</View>

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

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.

1import React, { useState } from 'react';
2
3// ...
4export default function App() {
5 const [value, setValue] = useState('');
6 const [todos, setTodos] = useState([]);
7
8 addTodo = () => {
9 if (value.length > 0) {
10 setTodos([...todos, { text: value, key: Date.now(), checked: false }]);
11 setValue('');
12 }
13 };
14
15 // ...
16}

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.

1import React, { useState } from 'react';
2import {
3 StyleSheet,
4 Text,
5 View,
6 TouchableOpacity,
7 TextInput
8} from 'react-native';
9
10import Icon from 'react-native-vector-icons/Feather';
11
12export default function App() {
13 const [value, setValue] = useState('');
14 const [todos, setTodos] = useState([]);
15
16 addTodo = () => {
17 if (value.length > 0) {
18 setTodos([...todos, { text: value, key: Date.now(), checked: false }]);
19 setValue('');
20 }
21 };
22
23 return (
24 <View style={styles.container}>
25 <Text style={styles.header}>Todo List</Text>
26 <View style={styles.textInputContainer}>
27 <TextInput
28 style={styles.textInput}
29 multiline={true}
30 placeholder="What do you want to do today?"
31 placeholderTextColor="#abbabb"
32 value={value}
33 onChangeText={value => setValue(value)}
34 />
35 <TouchableOpacity onPress={() => handleAddTodo()}>
36 >
37 <Icon name="plus" size={30} color="blue" style={{ marginLeft: 15 }} />
38 </TouchableOpacity>
39 </View>
40 </View>
41 );
42}
43
44const styles = StyleSheet.create({
45 container: {
46 flex: 1,
47 justifyContent: 'flex-start',
48 alignItems: 'center',
49 backgroundColor: '#F5FCFF'
50 },
51 header: {
52 marginTop: '15%',
53 fontSize: 20,
54 color: 'red',
55 paddingBottom: 10
56 },
57 textInputContainer: {
58 flexDirection: 'row',
59 alignItems: 'baseline',
60 borderColor: 'black',
61 borderBottomWidth: 1,
62 paddingRight: 10,
63 paddingBottom: 10
64 },
65 textInput: {
66 flex: 1,
67 height: 20,
68 fontSize: 18,
69 fontWeight: 'bold',
70 color: 'black',
71 paddingLeft: 10,
72 minHeight: '3%'
73 }
74});

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.

1import React from 'react';
2import { StyleSheet, TouchableOpacity, View, Text } from 'react-native';
3import Icon from 'react-native-vector-icons/Feather';
4
5export default function TodoList(props) {
6 return (
7 <View style={styles.listContainer}>
8 <Icon name="square" size={30} color="black" style={{ marginLeft: 15 }} />
9 <Text style={styles.listItem}>{props.text}</Text>
10 <Icon
11 name="trash-2"
12 size={30}
13 color="red"
14 style={{ marginLeft: 'auto' }}
15 onPress={props.deleteTodo}
16 />
17 </View>
18 );
19}
20
21const styles = StyleSheet.create({
22 listContainer: {
23 marginTop: '5%',
24 flexDirection: 'row',
25 borderColor: '#aaaaaa',
26 borderBottomWidth: 1.5,
27 width: '100%',
28 alignItems: 'stretch',
29 minHeight: 40
30 },
31 listItem: {
32 paddingBottom: 20,
33 paddingLeft: 10,
34 marginTop: 6,
35 borderColor: 'green',
36 borderBottomWidth: 1,
37 fontSize: 17,
38 fontWeight: 'bold',
39 color: 'white'
40 }
41});

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.

1import {
2 StyleSheet,
3 Text,
4 View,
5 TouchableOpacity,
6 TextInput,
7 ScrollView
8} from 'react-native';
9
10// ...
11
12import TodoList from './TodoList';
13
14// ...
15return (
16 <View style={styles.container}>
17 {/* ... */}
18 <ScrollView style={{ width: '100%' }}>
19 {todos.map(item => (
20 <TodoList text={item.text} key={item.key} />
21 ))}
22 </ScrollView>
23 </View>
24);

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.

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.

1checkTodo = id => {
2 setTodos(
3 todos.map(todo => {
4 if (todo.key === id) todo.checked = !todo.checked;
5 return todo;
6 })
7 );
8};
9
10deleteTodo = id => {
11 setTodos(
12 todos.filter(todo => {
13 if (todo.key !== id) return true;
14 })
15 );
16};

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.

1// App.js
2<ScrollView style={{ width: '100%' }}>
3 {todos.map(item => (
4 <TodoList
5 text={item.text}
6 key={item.key}
7 checked={item.checked}
8 setChecked={() => checkTodo(item.key)}
9 deleteTodo={() => deleteTodo(item.key)}
10 />
11 ))}
12</ScrollView>

Now open, TodoList.js and these new props.

1import React from 'react';
2import { StyleSheet, View, Text } from 'react-native';
3import Icon from 'react-native-vector-icons/Feather';
4
5export default function TodoList(props) {
6 return (
7 <View style={styles.listContainer}>
8 <Icon
9 name={props.checked ? 'check' : 'square'}
10 size={30}
11 color="black"
12 style={{ marginLeft: 15 }}
13 onPress={props.setChecked}
14 />
15 <View>
16 {props.checked && <View style={styles.verticalLine} />}
17 <Text style={styles.listItem}>{props.text}</Text>
18 </View>
19 <Icon
20 name="trash-2"
21 size={30}
22 color="red"
23 style={{ marginLeft: 'auto' }}
24 onPress={props.deleteTodo}
25 />
26 </View>
27 );
28}
29
30const styles = StyleSheet.create({
31 listContainer: {
32 marginTop: '5%',
33 flexDirection: 'row',
34 borderColor: '#aaaaaa',
35 borderBottomWidth: 1.5,
36 width: '100%',
37 alignItems: 'stretch',
38 minHeight: 40
39 },
40 listItem: {
41 paddingBottom: 20,
42 paddingLeft: 10,
43 marginTop: 6,
44 borderColor: 'green',
45 borderBottomWidth: 1,
46 fontSize: 17,
47 fontWeight: 'bold',
48 color: 'black'
49 },
50 verticalLine: {
51 borderBottomColor: 'green',
52 borderBottomWidth: 4,
53 marginLeft: 10,
54 width: '100%',
55 position: 'absolute',
56 marginTop: 15,
57 fontWeight: 'bold'
58 }
59});

Now run the app and see it in action.

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.

You can extend this demo application by adding AsyncStorage or a cloud database provider and making this application real time. Also, do not forget to enhance the UI to your liking.

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.

amandeepmittal/RNHooksTODOAPP


More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. On this blog, I write about my learnings in software development and technical writing.

Currently, working maintaining docs at 𝝠 Expo. Read more about me on the About page.


Copyright ©  2019-2024 Aman Mittal · All Rights Reserved.