Jay Poojara
React Native

Know-Hows of React/React Native Hooks

May 2, 2020 4 min read

author:

Know-Hows of React/React Native Hooks

Reading Time: 4 minutes

React/React Native Hooks are a type of function first introduced in React Native 16.8.0 release. The use of hooks in code is purely optional. However, it increases the readability of the code and facilitates its debugging. Interested in gaining more insight? Just follow on to explore the React Hooks Basics – what are Hooks, Why to use Hooks and a probable way to use them in your application. So, lets get started with React Hooks.

Getting started with React Hooks Basics

What Are Hooks?

Hooks are React Native components that help you use features like ‘states’ from within the functions. As a result, you need not convert your function into a class, say, to add a new ‘state’ to it. Hooks offer you a more direct API approach to control, and even combine, React Native concepts like states, refs, context, and life cycle, without using classes.

Why use Hooks?

Reactive native is not very user-friendly when it comes to the matter of sharing stateful logic between the components or the community. The reason is, to imbibe the ‘re-usability’ factor into your React application, you need to make use of patterns like higher-order components and render props. This will often compel you to rearrange your component hierarchy, snatching-off simplicity from the code. Another issue with React Native code is related to life cycle methods. In most of the cases, the code snippets will be split-up based on their life cycle process rather than their functional relation. This clutters up the code with totally unrelated logical blocks.

Implementation of hooks into the React Native code can effectively address both these issues. Hooks can extract stateful logic from React components, relatively easily. They split-up your complex components into relatively simple, smaller functions, by considering their mutual connectivity rather than the process of the life cycle. These factors greatly ease the process of component re-usability, independent testing, code tracking, and debugging, without being prone to high-level abstraction. Besides, hooks are 100% backward compatible. They can successfully be implemented in one part of the code without affecting the overall functionality. Laden by these unique features, hooks stand as a promising React Native component that would help in building great apps.

How to Use Hooks?

To understand how to use Hooks, you will be presented with an example of creating a simple form in the React Native environment. First, you will be explained the traditional method of coding that makes use of this.state component. Next, you will be introduced with a method to exploit the potential of a built-in hook, useState, to implement equivalent functionality. Lastly, you will be exposed to a technique of using the hook useEffect to update the data fields in the code.

Let us Create a React Native App .

  • Let us start our React Native code by prompting the user to enter the first and the last names. In the usual method of coding, this would require you to define and initialize two state variables: firstName and lastName, using this.state, as shown in the following code snippet.
constructor(props) {
	super(props);
	this.state = {
		firstName: '',
		lastName: ''
	};
}
  • Next, you will be required to add them as a value for TextInput and its text change event.
<TextInput
        placeholder='First Name'
        style={input}
        value={firstName}
        onChangeText={(text) =>{
         this.setState(
             {
                 firstName: text
             })
   }}
/>

Now, if you want to develop the same form using useState hook, then

  • You need to first import useState from react
import React, {useState} from 'react';
  • Following it, you will have to call useState to declare state variables. In this case, we have two of them: firstName and lastName. So, useState must be called twice by being supplied only with relevant initial states as its input arguments. However, it is to be noted that unlike in the case of classes, these states need not compulsorily be objects.
  • Such a call to useState would return you a pair of values: current state (or value) and a function that can be used to update its value.
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
  • Next, you would need to code TextInput part, but by making use of useState instead of this.state.
<TextInput
        placeholder='First Name'
        style={input}
        value={firstName}
        onChangeText={text => setFirstName(text)}
/>

That’s it!! It’s done. Here is the bird’s eye view showing both the codes. Just execute them and analyze their operational equivalence.

In traditional React Native code, we cannot perform the operations like data fetching or manual changing of DOM while rendering. This is because, if done, they would affect other components adversely. Hooks offer a potential solution to this problem as the apps based on hooks can perform these side effects from function components. This eliminates the need to run additional code after performing the functions like updating the DOM.

So, now, let us use useEffect hook to update our fields with new values instead of using componentDidMount and componentDidUpdate. For this, at first, you need to import useEffect from react, just as you did while using useState.

import React, { useState, useEffect } from 'react';

Next, you will have to call useEffect hook by passing an array of values impacting the effects as its second argument.

useEffect(() => {
   setName(`${firstName} ${lastName}`);
}, [firstName, lastName]);

Such a call to useEffect instructs the React to run your effect function after your DOM is updated. By default, these effects are run after every completed render. Nevertheless, you can even configure them to run only when certain values get changed.

Note: The codes presented in the work are available on the master branch of my Github account in react-native-hooks-demo repository. Feel free to browse through!

Hello, I am Jay Poojara, a professional Android, Laravel, NodeJS, EmberJS & React Native Developer. I am a very enthusiastic learner about the latest web and mobile technologies and a big fan of PS4 and Movies.
Leave a comment

Your email address will not be published. Required fields are marked *