Ref Hooks provide a way to access and interact with the DOM (Document Object Model) nodes directly within functional components. Before hooks, refs were primarily used in class components. However, with Ref Hooks, functional components can also take advantage of this capability, enhancing flexibility and simplifying code.
- useRef is used to create mutable references that persist across renders in functional components.
- useImperativeHandler customizes the instance value that is exposed when using
ref
with functional components.
We will discuss about the following types of Ref Hooks in React.
useRef Hooks:
The useRef hook is a feature in React that provides a way to access and interact with a DOM element or a React component instance directly. It returns a mutable ref object whose current property is initialized with the passed argument (initially undefined). The current property can then be modified to reference a DOM element or a component instance.
- Access DOM Elements: If you need to do something specific with a certain HTML element, like focusing on an input field or measuring its size,
useRef
lets you get a reference to that element so you can work with it directly. - Store Values without Triggering Re-renders: Sometimes, you might have values that change but you don't want them to cause your component to rerender. With
useRef
, you can store these values, and when they change, they won't automatically trigger a rerender. - Work Outside of the Regular React Flow: While React encourages a declarative approach, sometimes you need to do things imperatively, like triggering animations or working with third-party libraries.
useRef
helps you do this by providing a way to work with elements outside of React's usual flow.
Syntax:
const refContainer = useRef(initialValue);
Example: Below is an example of useRef Hooks that can access the DOM elements.
JavaScript
// App.js
import React, {
Fragment,
useRef
} from 'react';
import './App.css';
function App() {
const focusPoint = useRef(null);
const onClickHandler = () => {
focusPoint.current.value =
"Welcome to GeeksforGeeks!";
focusPoint.current.focus();
console.log("Textarea ref:",
focusPoint.current);
};
return (
<Fragment>
<div className="container">
<button onClick={onClickHandler}>
ACTION
</button>
<label>
Click on the action button to
focus and populate the text.
</label>
<br />
<textarea ref={focusPoint} />
</div>
</Fragment>
);
};
export default App;
CSS
/* App.css */
.container {
margin: 50px auto;
width: 80%;
max-width: 600px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
button {
padding: 10px 20px;
font-size: 16px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
textarea {
width: 100%;
height: 200px;
margin-top: 10px;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
resize: vertical;
}
Start your application using the following command.
npm start
Output:
OutputuseImperativeHandler Hooks:
The useImperativeHandler
hook is a feature in React that allows you to define custom imperative methods that can be called from parent components. It's particularly useful when you need to expose specific functionalities of a child component to its parent in a controlled manner.
- Defining Custom Methods: With
useImperativeHandler
, you can define custom functions inside a child component that the parent component can call directly. This is helpful when you want to encapsulate certain functionalities within the child component but still allow the parent to interact with them. - Controlled Exposures: Unlike traditional component methods, the methods defined using
useImperativeHandler
are exposed explicitly by the parent component. This means the parent has full control over when and how these methods are accessed, which can be crucial for maintaining a clear and predictable component interface.
Syntax:
useImperativeHandle(ref, createHandle, [deps])
Example: Below is an example of useImperativeHandler hooks.
JavaScript
import React, {
useRef
} from 'react';
const App = () => {
const inputRef = useRef(null);
return (
<div>
<Input onFocus={() =>
inputRef.current.focus()}
ref={inputRef} />
</div>
);
};
export default App;
JavaScript
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);
Output:
Output
Similar Reads
Resource Hooks in React In React, components often need to access external resources such as data from promises or context information for styling. Managing these resources within the component state could lead to unnecessary complexity and performance overhead. React provides a simple solution with the 'use' hook to overc
3 min read
Built-in React Hooks In React, built-in Hooks are like tools that empower your components with various functionalities. They give you the flexibility to use different features without having to create class components. You can either utilize the hooks provided by React or mix and match them to create custom hooks tailor
5 min read
New Hooks in React 18 React's state, representing dynamic component data, is integral for effective component management. Initially confined to class components and managed using this.setState, the introduction of React Hooks in version 16.8 extended state usage to functional components. Hooks, functions enabling state a
5 min read
Introduction to React Hooks In React, Hooks are functions that allow you to manage state and perform side effects without the involvement of class components. Hooks were introduced in v16.8 of React and they can be accessed only through functional components but not through class components (Hooks were specifically designed fo
7 min read
How to create refs in React JS? React JS, a powerful and declarative JavaScript library for building user interfaces, provides a feature known as "refs" that allows developers to interact with the underlying DOM elements directly. Refs are generally used for the following purposes:Managing focus, text selection, or media playback.
4 min read