In React, useRef
is a hook that returns a mutable object with a .current
property. This object persists across renders and can store any value, such as DOM elements or data that should not trigger a re-render when changed. Essentially, useRef
allows you to persist values or references that do not need to update the component state.
Here’s a breakdown of when and why you might use useRef
:
- DOM Manipulation: You can access and manipulate DOM elements directly.
- Storing mutable values: Store values that you don’t want to trigger a re-render when they change.
- Persist values between renders: Values stored in
useRef
are not reset when the component re-renders.
Example : Employee Input Form
Let’s create a scenario where we have a form that collects employee information, and you want to store some input element references without causing the component to re-render every time the reference changes.
We will:
- Create an
Employee
object. - Use
useRef
to store references to input fields (e.g., employee name and department). - Show how to access and update these fields using
useRef
.
import React, { useRef, useState } from 'react';
function EmployeeForm() {
// Using useState to manage the employee object.
const [employee, setEmployee] = useState({
name: '',
department: ''
});
// useRef for storing…