useRef and useImperativeHandle in React.

Aman
Catalysts Reachout
Published in
4 min readOct 24, 2022

State Management is the place where most of the development in react revolves around, so as, to make the webpage dynamic. To manage the states, we use Hooks so that it will re-render the page on changing the states of the props to bring the corresponding effect. But How does React (or we)trigger the re-rendering of the component?

Resource:- Reacjs.org

Re-rendering of the component.

Hooks in react, are mostly immutable. Then which other hooks are mutable ? To the point of the fact, only useRef is the one which is mutable. If someone knows something else then they can correctify me by commenting.

Mutable and Immutable.

Mutable means the ability to change. So , in mutable hook we can change the instances of the same object without making new object and updating it. That’s why , useRef does not re-render on state change. Whereas , Immutable hooks like useState , useEffect brings up the Re-rendering on the changes of the states because they practice immutability.

What is useRef ?

It is one of the hooks in React which does not promote re-rendering on differences in the state of the props. It accepts one argument as initial value and returns a reference. A reference is an object having a special property current.

import React, { useRef } from 'react'const UseRef = () => {const inputRef = useRef() // accepts null as initial value and returns reference to inputRefconst onClick = () => {console.log(inputRef.current.value); // using inputRef current property to get value of inputRef current value.}return (<div><h1>Pedro</h1><input type="text" placeholder="Ex..." ref={inputRef} /> // attaching 'inputRef' as a ref to access input element <button onClick={onClick}>Change Name</button></div>)

Some use cases of useRef() : -

  • Accessing virtual DOM elements like focusing on input when clicked on it.
  • implementing a stopwatch.
  • Clicking button multiple times just to navigate to some other links.

So, by above use cases , we can deduce that useRef does not promote re-rendering on changes and adding points to the performance of the application.

Passing of props in a flow → → →

In React, the data flow is unidirectional going top-down in the component tree. It means that a parent component can configure a child component thanks to properties (props).
So in a sense, a child can have access to an element of the parent when passed as property. But a parent can’t have access to an element of the child, or so you think.

Resource:-https://dev.to/romaintrotard/useimperativehandle-the-most-unknown-react-hook-3po6
Note : - We can inverse the data flow, by passing callback and value, this is called "lifting state up".

To give the parent access to an element of the child , we use useImperativeHandle() hook. Let’s have a look on the code firstly.

Button.js file code

import React , {forwardRef, useImperativeHandle, useState} from 'react'const Button = forwardRef((props,ref) => {useImperativeHandle(ref , () => ({alterToggle(){setToggle(!toggle);}}))const [toggle,setToggle] = useState(true);return (<><button>Button from child</button>{toggle && <h1>Toggle</h1>}</>)})export default Button

UseImperativeHandle.js file code

import React, {useRef} from 'react'import Button from './Button';const UseImperativeHandle = () => {const buttonref = useRef(null);return (<><button onClick={() => buttonref.current.alterToggle()}>Button from Parent</button><Button ref = {buttonref}/></>)}export default UseImperativeHandle

Output:-

As we can see , we are accessing props defined in child component inside in parent component.

When to use useImperativeHandle In React?

When it comes to using useImperativeHandle, it is actually pretty rare and won’t need to be used very often.

You should generally try to avoid using this hook as well for the most part, if you feel the need to modify a native property on a ref, there will most likely be another way in which you can do this without directly modifying the ref.

For example, if you want to fire a tracking event onClick, instead of using useImperativeHandle with a forwarded ref you can try adding the onClick function as a property of that DOM element instead.

Outside of that when you need to change/modify some values within a ref of a DOM element, then it might be worth using useImperitiveHandle with a ref providing there is no other way to do this.

Finally, if you are using useImperativeHandle, then you should only use it in combination with the forwardRef HOC.

That’s it was. To make readers aware about useImperativeHandle and its rare use.

--

--