Introduction to useRef() And Custom Hook In ReactJS

Introduction

In the previous article, we learned about useMemo() hook and how it is used in ReactJS. Now, in this article, we will be learning about useRef() hook, why this hook is required and how it can be implemented in ReactJS. 

useRef() hook

In React, useRef() hook is used to access DOM nodes or HTML elements. The purpose of this hook is to interact with DOM elements like accessing the input element value or focusing on the input element.

useRef() hook returns a mutable ref objects of which .current property is initialized to passed argument (initialValue). The returned object will persist for the full time of the component.

Let’s look at the demo. We want to focus on an input element as soon as the page loads. To achieve this, we need to define the logic in useEffect() hook and also, keep in mind that it should be done only once so let’s look at the code below. 

So, to implement the useRef hook, we must follow 3 steps.

  1. Import useRef hook.
  2. Create a constant variable with useRef as null.
  3. Use your created variable as a Node presentor.

Create a component named InputFocus.js,

import React,{useEffect,useRef} from 'react'  
  
function InputFocus() {  
      
  const inputRef = useRef(null)  
    
  useEffect(() => {  
     inputRef.current.focus()  
  }, [])  
  
    return (  
        <div>  
            <input ref={inputRef} type="text"/>  
        </div>  
    )  
}  
  
export default InputFocus  

And, include the same component in App.js.

import React from 'react';  
import './App.css';  
import InputFocus from './components/InputFocus';  
  
function App() {  
  
  return (  
    <div className="App">  
     <InputFocus/>  
    </div>  
  );  
}  
  
export default App;  

Now, run the application and see in the browser.

useRef() And Custom Hook In ReactJS

As you can see in the image, the cursor is displaying, so useRef() hook allows access to DOM and it will return the same element on every render.

However, keep in mind that useRef() hook does not notify any changes on the element as it does not re-render. If the user wants to perform any operation in the element during attaching and detaching to the node, it should implement the useCallback() hook.

So, until now, we have seen many hooks. Now, we will get to know about the concept of custom hooks. 

Custom Hooks

A custom hook is a function in React that starts with a keyword use and can include other hooks in it. Unlike for hooks on which we need to follow Rules of Hooks like:

  1. Hooks cannot be nested inside loops, conditions or other nested functions. It should be called on top-level
  2. Hooks can be called only in Functional component. We can’t call hooks from regular JavaScript functions.

But while creating your own custom hook we can use multiple hooks in our custom hook. 

Why do we require a custom hook?

  1. Custom hooks provide a simple alternative to Higher Order Component and Render props.
  2. Custom hook provides less repetitive code.
  3. Custom hook also provides fewer keystrokes.

How to create custom Hooks?

While creating a hook in ReactJS, we will create a hook folder under src folder.

useRef() And Custom Hook In ReactJS

After creating the hooks folder, we can create our custom hooks. Let’s look at the purpose of Hooks and why it is required to create a custom hook.

We will create a UserForm component that includes a name and profession textbox as below.

import React, { useState } from 'react'  
  
function UserForm() {  
    const [name, setName] = useState("")  
    const [proffession, setProffession] = useState("")  
  
    const submitCallback = e => {  
        e.preventDefault()  
        alert(`The proffession of ${name} is ${proffession}`)  
    }  
  
    return (  
        <div>  
            <form onSubmit={submitCallback}>  
                <div><label>Name : </label>  
                    <input type="text" value={name} onChange={(e) => setName(e.target.value)} />  
                </div><br />  
                <div><label>Proffession : </label>  
                    <input type="text" value={proffession} onChange={(e) => setProffession(e.target.value)} />  
                </div>  
                <button type="submit"> Submit</button>  
            </form>  
        </div>  
    )  
}  
  
export default UserForm 

The output will be displayed as below.

useRef() And Custom Hook In ReactJS
useRef() And Custom Hook In ReactJS

Now, let’s create a custom hook for the input element. 

useInput.js

import { useState } from 'react'  
  
function useInput(initialValue) {  
    const [value, setValue] = useState(initialValue)  
    const reset = () => {  
        setValue(initialValue)  
    }  
  
    const bind = {  
        value,  
        onChange: e => {  
            setValue(e.target.value)  
        }  
    }  
  
    return [value, bind, reset]  
}  
  
export default useInput  

UserForm.js

import React from 'react'  
import useInput from '../hooks/useInput'  
  
function UserForm() {  
  
    const [name,bindName,resetName] = useInput("")  
    const [proffession,bindProffession,resetProffession] = useInput("")  
  
    const submitCallback = e => {  
        e.preventDefault()  
        alert(`The proffession of ${name} is ${proffession}`)  
        resetName()  
        resetProffession()  
    }  
  
    return (  
        <div>  
            <form onSubmit={submitCallback}>  
                <div><label>Name : </label>  
                    <input type="text" {... bindName} />  
                </div><br />  
                <div><label>Proffession : </label>  
                    <input type="text" {...bindProffession} />  
                </div><br />  
                <button type="submit"> Submit</button>  
                  
            </form>  
        </div>  
    )  
}  
  
export default UserForm 

The output will remain the same as it was previously.

useRef() And Custom Hook In ReactJS
useRef() And Custom Hook In ReactJS
useRef() And Custom Hook In ReactJS

So, we have seen how much we have minimized the code and reduced code repetition. This way, we can write custom hooks which prevent code repetition and provide code minimization. We can write custom hooks for many implementations like generating sliders, generalizing function or any task implementation. 

Summary

In this article, we have learned about useRef hook and the process of creating a custom hook in ReactJS.

With this article, I’ve finished the concept of React Hooks. Now, I will move on to the learning of Redux in ReactJS. If you have any confusion or suggestions, please do comment.

Any question or feedback or suggestion, please do comment and let me know.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s