React Native – How To Use Hooks In React Native ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Use Hooks In React Native ?).

In this article, we will understand about how to use Hooks in react native. Hooks are specially-implemented functions that let us add functionality to React components beyond just creating and returning React elements. This article demonstrates the built-in hooks usage in react native application.

A famous quote about learning is :

” Develop a passion for learning. If you do, you will never cease to grow. “

So Let’s begin.


React Hooks

” React Hooks are a new addition in React 16.8 that let you use state and other React features without writing a class component. In other words, Hooks are functions that let you “hook into” React state and lifecycle features from function components. (They do not work inside class components.)”

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. It mainly uses to handle the state and side effects in react functional component. React Hooks are a way to use stateful functions inside a functional component. Hooks don’t work inside classes — they let you use React without classesReact provides a few built-in Hooks like useState and useEffect. The React hooks do :

  • Best practices
  • Easy to under understand
  • Easy to test
  • Increases the performance and so on.


Rules and Linting

Hooks aren’t regular functions; they have to be written in a certain way. To dive deeper into this topic, check out:

ReactJS – How to Effectively Think In React Hooks ?

When using hooks, we typically want to use eslint and the react-hooks plugin. Hooks are powerful, but can be unintuitive at first, and this tool catches a lot of mistakes before we ever run our code.


In-built React Hooks APIs

We’ll look at the following built-in hooks in more detail:

  • useState – Persist state within a component function
  • useReducer – Similar to useState, but for state that involves multiple sub-values
  • useEffect – Perform side effects within our component functions
  • useRef – Wrap a mutable value


1. useState

The useState hook lets us “remember” a value within a component function. Since our component function may be called many times throughout the lifecycle of the component, any variable we declare normally (i.e. with let myVar = ...) will get reset. With useState, React can remember a state variable for us, making sure it gets passed into our component instance correctly.


API

The useState hook takes a single argument, our initial state, and returns an array containing two elements:

  • state – the current state
  • setState – a function to update our state

Syntax –  const [state, setState] = useState(initialValue)


Example

In this example, we’ll use useState to append to an array.

The useState hook can store any type of value: a number, a string, an array, an object, etc.

import React, { useState } from 'react'
import { View, Text, Button } from 'react-native'

const randomDiceRoll = () => Math.floor(Math.random() * 6) + 1

export default function App() {
  const [diceRolls, setDiceRolls] = useState([])

  return (
    <View>
      <Button
        title="Roll dice!"
        onPress={() => {
          setDiceRolls([...diceRolls, randomDiceRoll()])
        }}
      />
      {diceRolls.map((diceRoll, index) => (
        <Text style={{ fontSize: 24 }} key={index}>
          {diceRoll}
        </Text>
      ))}
    </View>
  )
}

The result of above example is displayed below :


Updating mutable state values

Note how when we call setDiceRoll, we’re not pushing the integer returned from randomDiceRoll() into the diceRolls array. Instead, we return a new array containing the destructured diceRolls array and the newly randomized dice roll. Why?

Hooks can tell React to re-run our component function and update the UI. The useState hook tells React to re-run our component function whenever we call setDiceRolls with a different value. Internally, useState then compares the current value of diceRolls with the value we passed to setDiceRolls using ===. If we’re using a mutable value like an array, and we only change its contents, useState won’t detect that change and won’t tell React to re-run our component function. This will result in our UI displaying old/stale data. To avoid this problem we need to create a new array, so that useState will detect that our data changed and display the newest data.


2. useReducer

The useReducer hook is similar to useState, but gives us a more structured approach for updating complex values.

We typically use useReducer when our state has multiple sub-values, e.g. an object containing keys that we want to update independently.


API

The useReducer hook requires 2 arguments, and has an optional 3rd argument:

  • reducer – a pure function that takes a state and an action, and returns a new state value based on the action
  • initialState – any initial state value, just like useState
  • initializer (optional) – a function called to lazily instantiate the initialState (this is uncommon)

The useReducer hook returns the current state, and a dispatch function to update the state.


Example

In this example, we store both a first and last name in a single state object with useReducer.

When we type a new first name, dispatch is called with { type: 'first', value: text } as its argument. This argument gets passed to the reducer as action. Then the reducer follows the switch case logic case 'first' and returns the new state: the current last name (from ...state) and the new first name contained in the action as action.value.

import React, { useReducer } from 'react'
import { View, Text, TextInput } from 'react-native'

function reducer(state, action) {
  switch (action.type) {
    case 'first':
      return { ...state, first: action.value }
    case 'last':
      return { ...state, last: action.value }
  }
}

export default function App() {
  const [state, dispatch] = useReducer(reducer, { first: '', last: '' })

  return (
    <View>
      <TextInput
        style={{ fontSize: 32 }}
        placeholder="First"
        value={state.first}
        onChangeText={(text) => {
          dispatch({ type: 'first', value: text })
        }}
      />
      <TextInput
        style={{ fontSize: 32 }}
        placeholder="Last"
        value={state.last}
        onChangeText={(text) => {
          dispatch({ type: 'last', value: text })
        }}
      />
      <Text style={{ fontSize: 32 }}>
        Hello {state.first} {state.last}
      </Text>
    </View>
  )
}

The result of above example is displayed below :


3. useEffect

We use the useEffect hook to call functions with side effects within our components.


API

The useEffect hook takes 2 arguments:

  • callback – a function with side effects
  • dependencies – an optional array containing dependency values

When our component function runs, the callback will be called if any dependencies have changed since the last time the component function ran.


Example

In this example, we’ll log to the console any time the count is a multiple of 3. The callback is called every time the countEvery3 changes, since countEvery3 is listed as a dependency.

import React, { useState, useEffect } from 'react'
import { Button } from 'react-native'

export default function App() {
  const [count, setCount] = useState(0)
  const countEvery3 = Math.floor(count / 3)

  useEffect(() => {
    console.log(countEvery3)
  }, [countEvery3])

  return (
    <Button
      title={`Increment ${count}`}
      onPress={() => {
        setCount(count + 1)
      }}
    />
  )
}

The result of above example is displayed below :


Undefined or empty dependency array

If the dependency array is empty or undefineduseEffect will have a different behavior:

  • [] – the callback is called only once, right after the component renders for the first time.
  • undefined – the callback is called on every component render (every time the component function runs).


undefined dependencies

Here the dependency array is undefined, so our callback will run every time our component function runs, e.g. any time we click the button and useState tells our component to re-run.

import React, { useState, useEffect } from 'react'
import { Button } from 'react-native'

export default function App() {
  const [count, setCount] = useState(0)

  useEffect(() => {
    console.log('Incremented!')
  })

  return (
    <Button
      title={`Increment ${count}`}
      onPress={() => {
        setCount(count + 1)
      }}
    />
  )
}

The result of above example is displayed below :


Empty dependencies

Here the dependency array is empty, so our callback will only run once (and therefore only log one time).

import React, { useState, useEffect } from 'react'
import { Button } from 'react-native'

export default function App() {
  const [count, setCount] = useState(0)

  useEffect(() => {
    console.log('Only once!')
  }, [])

  return (
    <Button
      title={`Increment ${count}`}
      onPress={() => {
        setCount(count + 1)
      }}
    />
  )
}

The result of above example is displayed below :


4. useRef

With useRef, we can create and update a single mutable value that exists for the lifetime of the component instance.

After assigning the ref to a variable, we use .current to access the mutable value.


Example

In this example, we store the return value of setInterval, which is an interval id, so that we can later call clearInterval.

import React, { useState, useEffect, useRef } from 'react'
import { View, Text, Button } from 'react-native'

export default function App() {
  const intervalRef = useRef()
  const [count, setCount] = useState(0)

  useEffect(() => {
    intervalRef.current = setInterval(
      () => setCount((count) => count + 1),
      1000
    )

    return () => {
      clearInterval(intervalRef.current)
    }
  }, [])

  return (
    <View>
      <Text style={{ fontSize: 120 }}>{count}</Text>
      <Button
        title="Stop"
        onPress={() => {
          clearInterval(intervalRef.current)
        }}
      />
    </View>
  )
}

The result of above example is displayed below :


5. Custom Hooks

We can compose built-in hooks to create new ones. We should still use the use prefix for our function name.


Example

import React, { useState, useEffect, useRef } from 'react'
import { Text } from 'react-native'

function useInterval(callback, delay) {
  const savedCallback = useRef()

  // Remember the latest callback.
  useEffect(() => {
    savedCallback.current = callback
  }, [callback])

  // Set up the interval.
  useEffect(() => {
    if (delay !== null) {
      let id = setInterval(() => {
        savedCallback.current()
      }, delay)
      return () => clearInterval(id)
    }
  }, [delay])
}

export default function App() {
  const [count, setCount] = useState(0)

  useInterval(() => {
    setCount(count + 1)
  }, 1000)

  return <Text style={{ fontSize: 120 }}>{count}</Text>
}

That’s all about in this article.


Conclusion

In this article, We understood about how to use Hooks in React Native. This article demonstrated In-built Hooks APIs Usage with examples in React Native application.

Thanks for reading ! I hope you enjoyed and learned about the Hook Concepts in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING!!???

Loading

Summary
React Native - How To Use Hooks In React Native ?
Article Name
React Native - How To Use Hooks In React Native ?
Description
This article shows how to use Hooks in React Native. It demonstrates In-built Hooks APIs Usage with authentic examples in application.
Author

Leave a Comment