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 this variable as a Node Presenter.
Create a component named InputFocus.js,
  1. import React,{useEffect,useRef} from 'react'  
  2.   
  3. function InputFocus() {  
  4.       
  5.   const inputRef = useRef(null)  
  6.     
  7.   useEffect(() => {  
  8.      inputRef.current.focus()  
  9.   }, [])  
  10.   
  11.     return (  
  12.         <div>  
  13.             <input ref={inputRef} type="text"/>  
  14.         </div>  
  15.     )  
  16. }  
  17.   
  18. export default InputFocus  
And, include the same component in App.js.
  1. import React from 'react';  
  2. import './App.css';  
  3. import InputFocus from './components/InputFocus';  
  4.   
  5. function App() {  
  6.   
  7.   return (  
  8.     <div className="App">  
  9.      <InputFocus/>  
  10.     </div>  
  11.   );  
  12. }  
  13.   
  14. 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 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.
  1. import React, { useState } from 'react'  
  2.   
  3. function UserForm() {  
  4.     const [name, setName] = useState("")  
  5.     const [proffession, setProffession] = useState("")  
  6.   
  7.     const submitCallback = e => {  
  8.         e.preventDefault()  
  9.         alert(`The proffession of ${name} is ${proffession}`)  
  10.     }  
  11.   
  12.     return (  
  13.         <div>  
  14.             <form onSubmit={submitCallback}>  
  15.                 <div><label>Name : </label>  
  16.                     <input type="text" value={name} onChange={(e) => setName(e.target.value)} />  
  17.                 </div><br />  
  18.                 <div><label>Proffession : </label>  
  19.                     <input type="text" value={proffession} onChange={(e) => setProffession(e.target.value)} />  
  20.                 </div>  
  21.                 <button type="submit"> Submit</button>  
  22.             </form>  
  23.         </div>  
  24.     )  
  25. }  
  26.   
  27. 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
  1. import { useState } from 'react'  
  2.   
  3. function useInput(initialValue) {  
  4.     const [value, setValue] = useState(initialValue)  
  5.     const reset = () => {  
  6.         setValue(initialValue)  
  7.     }  
  8.   
  9.     const bind = {  
  10.         value,  
  11.         onChange: e => {  
  12.             setValue(e.target.value)  
  13.         }  
  14.     }  
  15.   
  16.     return [value, bind, reset]  
  17. }  
  18.   
  19. export default useInput  
UserForm.js
  1. import React from 'react'  
  2. import useInput from '../hooks/useInput'  
  3.   
  4. function UserForm() {  
  5.   
  6.     const [name,bindName,resetName] = useInput("")  
  7.     const [proffession,bindProffession,resetProffession] = useInput("")  
  8.   
  9.     const submitCallback = e => {  
  10.         e.preventDefault()  
  11.         alert(`The proffession of ${name} is ${proffession}`)  
  12.         resetName()  
  13.         resetProffession()  
  14.     }  
  15.   
  16.     return (  
  17.         <div>  
  18.             <form onSubmit={submitCallback}>  
  19.                 <div><label>Name : </label>  
  20.                     <input type="text" {... bindName} />  
  21.                 </div><br />  
  22.                 <div><label>Proffession : </label>  
  23.                     <input type="text" {...bindProffession} />  
  24.                 </div><br />  
  25.                 <button type="submit"> Submit</button>  
  26.                   
  27.             </form>  
  28.         </div>  
  29.     )  
  30. }  
  31.   
  32. 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. You can download the source code attached to this article. 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.