Contenido del Curso
React Mastery
React Mastery
useRef Hook
The useRef
hook allows us to create a variable that holds a reference to an element, a value, or any other data that doesn't affect the rendering of the component. This can be useful for storing mutable values, accessing DOM elements, or preserving values across component renders.
Syntax:
To utilize the useRef
hook, we declare a variable (refVariable
), and assign the result of invoking useRef()
to it. Optionally, we can provide an initial value (initialValue
) as an argument to this hook.
Note
The current value can be accessed and updated using the
refVariable.current
property. The beauty ofuseRef
is that it enables us to manipulate these values without triggering a re-render of the component.
Example:
Let's create the FormInput
component that uses the useRef
hook to create a reference to an input element and focuses on it when a button is clicked.
In this example, the useRef
hook creates a reference called inputRef
. This reference is assigned to the ref
attribute of the input
element, allowing us to access the input
element using inputRef.current
.
Line by line explanation:
- Line 1: We import the
useRef
hook from the React library to leverage its functionality; - Line 3: The
FormInput
component is defined using the conventional function syntax; - Line 4: We initialize the
inputRef
variable using theuseRef
hook, representing the input reference; - Lines 6-8: This JavaScript arrow function handles the logic for clicking the button, which focuses the user's cursor on the input field;
- Lines 10-15: The component's markup is rendered.
- On line 12, we set the reference using the
ref
attribute and assign theinputRef
variable as its value; - The button on line 13 utilizes the
onClick
attribute to specify the function to execute when clicked, which in this case is thehandleClick
function.
- On line 12, we set the reference using the
Full app code:
¡Gracias por tus comentarios!