Open In App

React.js useImperativeHandle Additional Hook

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The useImperativeHandle hook works in the similar phase of useRef hook but only it allows us to modify the instance that is going to be passed with the ref object which provides a reference to any DOM element. Although this hook is used in rare cases, it has some most advanced functionality.

Syntax:

useImperativeHandle(ref, createHandle, [deps])

Creating React Application:

  • Step 1: Create a React application using the following command.

    npx create-react-app functiondemo
  • Step 2: After creating your project folder i.e. functiondemo, move to it using the following command.

    cd functiondemo

Project Structure: It will look like the following.

Project Structure

Example: In this example, we are going to build a custom input button which on being in focus performs the custom user-defined. It is our custom input field which we will import in App.js file.

Input.js




import React, { useRef, useImperativeHandle, forwardRef } from 'react';
  
function Input(props, ref) {
  const btn = useRef();
  useImperativeHandle(ref, () => ({
    focus: () => {
      console.log('Input is in focus');
    },
  }));
  return <input ref={btn} {...props} placeholder="type here" />;
}
  
export default forwardRef(Input);


App.js




import React, { useRef } from 'react';
import Input from './Input';
  
const App = () => {
  const inputRef = useRef(null);
  return (
    <div>
      <Input onFocus={() => inputRef.current.focus()} 
      ref={inputRef} />
    </div>
  );
};
  
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

Reference:https://reactjs.org/docs/hooks-reference.html#useimperativehandle



Last Updated : 17 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads