React Native Hooks You Need to Know

React Native Hooks

React Hooks were first introduced in React 16.8.0 back in October of 2018. The React Hook API allowed developers to use state and many other React features without needing to write a class. The support for Hooks in React Native came in 0.59 build on March 12, 2019. Since its inception, React Hooks has earned its rightful place in the React Ecosystem and is used in several apps. Hence it is important to hire React Native developer who has deep knowledge and practical experience in integrating React Native hooks in different projects.

Hooks have enabled developers to enhance and expand the capabilities of functional components. With React Hooks, functional components are no longer stateless components and can use React features that were previously only accessible by React class components. Hence it combined the power of React class components and the neatness and straightforward approach of functional components to give developers a way to combine the benefits of both and keep the code easily readable and manageable.

Why are hooks important in React Native?

Any React Native developer, when developing a front-end mobile app in React Native, is bound to come across React hooks on many instances in the app development process. Although using React hooks or not is entirely optional, and you can continue using class components, it is still important to know how to use React hooks as it is a cleaner, more efficient, and faster way of getting the same task done. Hooks work the same way in React Native as they do in React. It is important to know about the basic out-of-the-box React Native hooks and other specific hooks built for React Native by the React Native community.

Basic React Native Hooks you need to know.

As mentioned in the React Hooks documentation, React has three basic hooks. You should know about their function and purpose –

1. useState

For any React app you are working on, its state is bound to change at multiple instances. This change can be in the value of an object, variable, or any other type of data present in your React component. For doing so, we need these changes to reflect in the DOM for which we use React hook – useState.

Here is what it looks like –

function App() {

  const [age, setAge] = useState(19);

  const handleClick = () => setAge(age + 1)


  return

      <div>

          I am {age} Years Old

        <div>

        <button onClick={handleClick}>Increase my age! </button>

      </div>

   </div>

}

2. useEffect()

The useEffect() hook in React Native allows side effects in the functional components. If you are familiar with working with class components and React lifecycle methods, you must know about componentDidMount, componentDidUpdate, componentWillUnmount lifecycle methods. All these methods are handled by React hook useEffect() for functional components.

READ MORE -  What Java Developer Should Learn in 2021?

Here is what it looks like –

import React, { useState, useEffect } from “react”;

 

const UseEffectExample = () => {

  const [button, setButton] = useState("");


  //useEffect hook

  useEffect(() => {

    console.log("useEffect has been called!", button);

  });


  const onYesPress = () => {

    setButton("Yes");

  };


  const onNoPress = () => {

    setButton("No");

  };


return (

      <div>

        <button onClick={() => this.onYesPress()}>Yes</button>

        <button onClick={() => this.onNoPress()}>No</button>

      </div>

    );

};

 

export default UseEffectExample;

3. useContext

Another basic React Native hook that you need to be familiar with is context API. React Native follows a component tree structure with many components from top to bottom of the app architecture. Out of these components, App Component is treated as a Parent Component, and all components within it are referred to as Child Components. Now React follows uni-directional data flow, which means any data passed as props needs to be passed through components from top to bottom.

This is not much of an issue if you have relatively lesser components; however, for bigger projects where there are 10-20 component levels, this method can be very inefficient. Hence, to solve this issue, React provides context, allowing passing the data directly to the targeted component without passing it down to all levels.

Here is what it looks like –

/ import useContext (or we could write React.useContext)

import React, { useContext } from ‘react’;

 

// old code goes here

 

function Display() {

const value = useContext(NumberContext);

return <div>The answer is {value}.</div>;

}

Top React Native Hooks you need to know.

Now that you know the basic React Native hook functions, we can move on to some of the other Top React Native hooks available in the React ecosystem and serve different purposes in your React Native app development project. We have shortlisted the best ones, so you don’t have to go through the hassle yourself –

1. useKeyboard Hook

useKeyboard is an effective React Native hook for apps with TextInput components and forms. If your React Native app has instances where the user’s keyboards pop up frequently, you can use this hook which eliminates the need to use Keyboard event listeners to know when the keyboard remains hidden or shown.

Here is what it looks like –

import { useKeyboard } from ‘@react-native-community/hooks’

const keyboard = useKeyboard()

 

console.log(‘keyboard isKeyboardShow: ‘, keyboard.keyboardShown)

console.log(‘keyboard keyboardHeight: ‘, keyboard.keyboardHeight)

console.log(‘keyboard coordinates: ‘, keyboard. coordinates)

2. useAppState Hook

This React Native hook helps developers determine if the app is currently in an active state or if the user is running the app in the background. Before introducing hooks, developers had to rely on App State API from React Native and add multiple event listeners to determine app activity status.

Here is what it looks like –

import { useAppState } from ‘@react-native-community/hooks’

const currentAppState = useAppState()

3. useDimensions Hook

Another handy React Native hook to know is the useDimensions hook. Before using hooks, developers used Dimensions API, which is available out-of-the-box with React Native. The purpose of Dimensions API is to understand the height and width values of the user device. When developers use the useDimensions hook, it comes with a listener that changes the dimensions as per the device orientation if it changes at any given point. We can also use the useWindowDimensions hook, available out-of-the-box with React Native.

READ MORE -  Things to Expect from A Custom Software Development Company

Here is what it looks like –

useDimensions Usage

import { useDimensions } from ‘@react-native-community/hooks’

const { width, height } = useDimensions().window

// or

const screen = useDimensions().screen

useWindowDimensions Usage

import {useWindowDimensions} from ‘react-native’;

const windowWidth = useWindowDimensions().width;

const windowHeight = useWindowDimensions().height;

4. useColorScheme Hook

useColorScheme React hook is the alternative solution for using Appearance API. The purpose of using Appearance API was to provide information about the user’s preference on the app color scheme (light/dark). useColorScheme is capable of obtaining this information and also act upon the identified preference of user and change it on the user’s phone accordingly.

Here is what it looks like –

import {Text, useColorScheme} from ‘react-native’;

const colorScheme = useColorScheme();

5. useMemo

useMemo is a React Native hook that returns a memorized value that can be passed in any “create” function and many dependencies. The returned value only uses the memorized value again if any dependency in the dependency tree is updated or changed.

import { useState, useMemo } from “react”;

import ReactDOM from “react-dom/client”;

 

const App = () => {

const [count, setCount] = useState(0);

const [todos, setTodos] = useState([]);

const calculation = useMemo(() => expensiveCalculation(count), [count]);

 

const increment = () => {

setCount((c) => c + 1);

};

const addTodo = () => {

setTodos((t) => […t, “New Todo”]);

};

 

return (

<div>

<div>

<h2>My Todos</h2>

{todos.map((todo, index) => {

return <p key={index}>{todo}</p>;

})}

<button onClick={addTodo}>Add Todo</button>

</div>

<hr />

<div>

Count: {count}

<button onClick={increment}>+</button>

<h2>Expensive Calculation</h2>

{calculation}

</div>

</div>

);

};

 

const expensiveCalculation = (num) => {

console.log(“Calculating…”);

for (let i = 0; i < 1000000000; i++) {

num += 1;

}

return num;

};

 

const root = ReactDOM.createRoot(document.getElementById(‘root’));

root.render(<App />);

 

To Summarize

These are some of the top React Native hooks that you should know about and use while developing your React Native apps. Such hooks ease the development process while helping maintain code readability and preciseness. It also provides an easier approach to solving complex React Native development issues. Make sure to go through other React Native hooks to find out the best-suited ones for your app requirements.

Ronak Patel Author

Ronak Patel is the CEO and Founder of Aglowid IT Solutions, an ever-emerging Top Web and Mobile Development company with a motto of turning clients into successful businesses. He believes that the Client’s success is the company’s success and so he always makes sure that Aglowid helps their client’s business to reach its true potential with the help of his best team with the standard development process he set up for the company.

 

Ganesh Kolekar is a graduate and geek. He is the man behind keeping the quality of the posts and manages the content part on the website.

Leave a Reply

Your email address will not be published.