React Native Hooks to Build React-Native App.

Build a React-Native App with the Help of React Native Hooks.

Hire React Native developer to extract component logic into reusable functions without writing a class.

React Native has introduced React Hooks that are functions to let you hook into React Native state and lifecycle features from the function components. React hooks don’t perform into classes that allow you to use React native without classes. Now it is available to use in React Native from version 0.59.

Prerequisites

  1. Basics of React Native
  2. Functional and class components, props, state and etc.
  3. Class components have their own built-in lifecycle that functional components don’t have. Now, if you want to use state inside the Functional Components, then you simply can’t.
  4. So now, you may want to know how we can use the state and same lifecycle in Functional Components like classes.

Introducing Hooks

Allow you to create every Component as a functional component.

Hooks are a new feature addition in React Native version 16.8, which allows you to use React Native features without having to write a class.

Ex. State of Component

Previously you could use state only within a class component. With hooks, our complexity with developing the application is very less. What you should keep in mind is that hooks don’t work inside classes.

Why Hooks?

  • Different ways of doing the same things.
  • No more complex lifecycle methods.
  • Simpler code. No more mapStateToProps, mapDispatchToprops with Redux.
  • Hooks avoid the whole confusion with ‘this’ keyword.
  • Hooks allow you to reuse stateful logic without changing your component hierarchy.
  • Hooks let us organize the logic inside a component into reusable isolated units.

Now let’s learn how we move from a class to a functional component.

From “class” to ()=>{…}

Map Lifecycle class methods to lifecycle hooks

There are 03 stages of the lifecycle:

1. Initial Render
getDerivedStateFromProps
useEffect( ()=>{},[propp1, prop2])
componentDidMount
useEffect( ()=> {},[])
2. Updates
getDerivedStateFromProps
useEffect( ()=>{},[propp1, prop2])
shouldComponentUpdate()
useMemo()
componentdidUpdate()
useEffect( ()=>{})
getSnapshotBeforeUpdate
custom Hook to hold previous state
3. Unmount
useEffect( ()=>{return()=>{//cleanup}},[])

So with hooks, we can do all the things which we are doing with classes. Like, Local state, effect, context to useState, useEffect, and useContexrt.

Let’s just list out all hooks:

Basic React Native Hooks:

(1) useState
(2) useEffect
(3) useContext

Additional Hooks:

(1) useReducer
(2) useCallback
(3) useMemo
(4) useRef
(5) useImperativeHandle
(6) useLayoutEffect
(7) useDebugValue

useState

useState is like this.state() in class. We are going to use useState instead of this. State to update the state value.

Unlike the class, the state is not an object here. We have to initialize the useState() with some value. It is a number or string whatever we want.

If you have to store multiple values, then for each value, you have to call useState().

Syntax : Const [data, setData] = useState( //value )

Make more sense; let’s learn one example:

Here, this example declares a state variable name initialized with an empty string. When writing in the text input name, variable value will be changed.

useEffect

useEffect is worked as per class lifecycle componentDidMount, componentWillUnMount, componentdidUpdate.

useEffect is just re-render the Component and changing the state variable’s value.

uesEffects accepts two arguments and doesn’t return anything. The first argument is a function that holds the code whatever you want to execute at run time.

The second argument is optional when you want to execute the hooks.

If you do not pass anything to this argument, then your function will be called on mount and every update.

The above example shows how we can apply useEffect in functional components. Interval time, the state value will be changed.

useEffect() is a side effect. You can use useEffect for event-handler and change the state value when we want.

useContext

This is another basic hook if anyone is not familiar with context API in react native. First, let’s have a look at it.

Consider an application with lots of components. App Component is our parent component, and within this Component, there are some child components.

So here we have several components; on the first level, we have A, B, and D Components. Nested within component B is component C and nested within component D is component E, and as per image component, F is nested inside component E.

So we have three levels of components here, in components A, C and F have requirements to display the userName. For this requirement, we need to pass the useName as the props to each Component.

For component A it’s pretty straight forward to directly pass the props.

For component C, we have to pass the props first to component B, then we can use it in Component C, as the same for component F to pass the props further down.

Here in this example, we have just a few nested components. Imagine if we have 10 to 20 level components, then all the components in between we have to forward the props. This is an inappropriate thing that might cause the problem, and code will be more confusing. So here, one solution for this context comes to the picture.

With context, you can pass the data directly to the Component without passing them to every level.

It’s finally time to learn useContext hook,

const value = useContext(MyContext);

Don’t forget that the argument to useContext must be the context object itself.

Now let you get some basic knowledge about Additional Hooks.

useReducer

This additional hook is work from state management. Okay, now don’t we already have a useState for state management? Let’s clear your head with useReducer is an alternative to useState. So our next question would be what’s the difference between them. Answer to this question we’ll have after this example. useReducer is meant for the reducers. We all know the reducer in javascript.

Reduce in javascript have array.reduce(reducer, initial value)

Summary for useReducer

useReducer is a hook that is used for state management

useReducer is related to reducer function

useReducer(reducer, initialState)

reducer(currentState, action)

Let’s have an example for a better understanding, here we are going to take counterexample again.

From this example, we can handle the different actions at once with useReducer. Run this project, and we can increment the count value by clicking on the increment button and the same as with decrement and reset button.

I think now we have some clear points about the useReducer, so let’s get the answer useState vs. useReducer.

  1. Depends on the type of state. If you need to use string, boolean or number value, then must use useSate. And if array or object, then must use useReducer.
  2. The second scenario depends on the number of transitions. If you are updating one or two states, then use useState. And if too many updates, then use useReducer.
  3. The third one depends on the business logic for the state transition if you do the complex transition or transfer value old to the new, then better to use useReducer.
  4. Fourth is for Local or Global State. If your state is within the one Component, then you can use useState, and if your state is at a global level, then you must use useReducer. It is better to use, and code will be reduced
import React, { useCallback } from 'react'

Every render of the Component, functions is recreated with it every time. useCallback always returns the memoized version of the function. So after using useCallback function will only be changed when one of the dependencies has.

It is useful when some callbacks are passed to the child component, and with that, you can prevent the unnecessary renders every time. This hook prevents unnecessary re-render of the function every time when it calls.

Just like useEffect, useCallback takes function and an array of dependencies as a parameter. If one of the dependencies value changes, only then functions return value will be changed; otherwise, it will always return the cached value.

If we have a parent component and inside parent component is child one. In the child component, we are passing one prop.

So when the parent component is re-render, every time props inside the child component will be called unnecessary. Here we can use the useCallback() hook to prevent this useless re-render.

useCallback(()=>{
dosomething()
},[dependencies])

Let’s go deeper for more understanding,

In the above example, the problem is that whenever the counter value is updated, all three functions are re-created. In this case, it is not a big problem to recreate the function unless we don’t have multiple functions.

For an application, this might be a big problem in performance for our app. For this problem, we can use useCallback().

So in the above example, we can warp all this function with useCallback():

So now you click any of the counters, the related state will be changed and re-initialized.for the better and prevent optimization, we can use the useCallback() hook.

useMemo

import React, { useMemo } from 'react'

useMemo() hook is just like useCallback() hook. Difference is useCallback returns memoized callback and useMemo returns memoized value.

If you are creating an application and have to process lots of data, then using this hook is a better choice. So it will work once at the first render in the application, and then the cached value will be returned every time.

So if you have userName to pass every time in the application components, then using the useMemo(), the operation will be done just once. Then state value will be stored in a memoized value, and when you want to use this value, you will get much faster!!

f
useMemo(()=>{
dosomething()
},[dependencies])

Remember that add an empty array as a parameter to useMemo(); otherwise, memoization will not happen. And if you want to pass arguments, then you also pass them in an array.

useRef

import React, { useRef } from 'react'
const refContainer = useRef(initialValue);

useRef is just like a container which can store mutable values in its .current property.

With Ref, we can access all the DOM nodes and their elements and also keeping a mutable variable. We all know about a ref in React Native. If you create createRef in the functional Component, then it will create a new instance at every render of DOM.

Updating a ref is a side effect. It has to be done inside the useEffect() or inside an event handler. However, the Component will not re-render when useRef value changes. For that, we can use useState().

Some Rules

“Only call Hooks at the top level.”

Don’t call hooks inside loops, conditions, or nested functions

“Only call Hooks from react native functions.”

Call hooks from React Native Components or Custom Hooks, don’t call it from regular functions

Wrapping Up

If you are looking for assistance to build a React native application with the help of React Hooks, then get in touch with us today. We are a globally renowned React Native development company, and we have well-versed React Native developers who have top of the line expertise in building React Native app with React Hooks. Hire React Native developers to use state, and other React features without writing a class. Our React Native developers have top-of-the-line expertise in building your own hooks to extract component logic into reusable functions.

Writer:https://medium.com/devtechtoday | Follower:https://medium.com/@bacancytechnology | Designer | Entrepreneur | Cycling | Reading | Digital Marketing