An essential topic of React Native

The Ultimate Guide to Custom Hooks in React Native

create your own hooks and perform a task more efficiently

custom hooks in react native
Photo by Lautaro Andreani on Unsplash

Background:

While developing an application, sometimes you face a problem in adding a feature. You find a third-party package to solve your problem but what if such a library doesn’t exist? Here custom hooks come in.

Custom hooks are encapsulated reusable functions that perform a specific task and return the results. Users can also pass inputs as parameters. It works just like a function.

Custom hooks are useful when the same code is used to call many times. Date conversion, sending emails, and calling an API are some examples of custom hooks.

custom hook meme

Practical:

Most of the application calls an API frequently in code. So, how to create a custom hook for API calls? Well, it’s easy. Let’s start.

Step 1: Import the existing hooks

Users can use existing hooks (useState, useEffect) to create a custom hook. It makes further steps more easier and efficient.

import { useEffect, useState } from "react";

Step 2: Create a function

Just like a functional component, create a function and export it. Pass parameters in parathesis if needed. The function will also return some results.

const requestHook = (url) => true;export default requestHook;

Step 3: React hooks

React useState is used to initialize and set the new values. Here 3 states will be using:

  • data state will contain API data
  • isLoading state will set the loader while fetching data from an API
  • error will return an error message if the request failed.

React useEffect use will to call an API. fetch method will take the URL and return the result of API data.

If the request is successful, it set the response to the data state. Else it set the error message to an error state. After that, it stops the loader and set the isLoading state to false.

Finally, it will return all the states.

const [data, setData] = useState(null);
const [isLoading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setTimeout(() => {
fetch(url)
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => setError(error))
.finally(() => setLoading(false));
}, 2000);
}, [url]);
return [data, isLoading, error];

here’s the complete custom hook for API calls:

Step 4: Import the custom hook

It’s time to use the custom hook. Import it where you want to use the API calling hook.

import React from "react";
import {
View,
Text,
StyleSheet,
FlatList,
ActivityIndicator
} from "react-native";
import requestHook from "./requestHook.js";function App() {

const [data, isLoading, error] = requestHook(
"https://jsonplaceholder.typicode.com/users"
);
return (
<View style={styles.app}>
{isLoading && <ActivityIndicator style={styles.loader} size="large" />}
{error && <Text style={styles.error}>Error: {error}</Text>}
{!isLoading && (
<FlatList
data={data}
renderItem={({ item }) => (
<View style={styles.item}>
<Text style={styles.title}>{item.name}</Text>
<Text style={styles.body}>{item.email}</Text>
</View>
)}
/>
)}
</View>
);
}
const styles = StyleSheet.create({
app: {
flex: 1
},
loader: {
flex: 1,
justifyContent: "center",
alignContent: "center"
},
item: {
backgroundColor: "#f9c2ff",
padding: 20,
marginVertical: 8,
marginHorizontal: 16
},
title: {
fontSize: 32
},
body: {
fontSize: 20
},
error: {
color: "red",
fontSize: 20,
textAlign: "center"
}
});
export default App;

Here’s the complete code of the custom hook example:

https://codesandbox.io/s/custom-hooks-react-native-dsu1wo

programming meme

Conclusion:

Custom hooks make the code reusable to use frequently. It saves time and increases readability. Overall, custom hooks add a lot of flexibility to write React apps more efficiently and better. Developers can use React built-in hooks to add additional functionalities to custom hooks.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bilal Ahmad

Bilal Ahmad

92 Followers

Full Stack MERN Developer | Google Cloud Lead | Freelancer