Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
useRef Hook | React Hooks and Context
React Mastery
course content

Course Content

React Mastery

React Mastery

1. Introduction to React Fundamentals
2. Styling in React Apps
3. React Hooks and Context
4. React in the Real World

bookuseRef 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 of useRef 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 the useRef 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.
    1. On line 12, we set the reference using the ref attribute and assign the inputRef variable as its value;
    2. The button on line 13 utilizes the onClick attribute to specify the function to execute when clicked, which in this case is the handleClick function.

Full app code:

1. What is the primary purpose of the `useRef` hook?
2. Which of the following best describes the behavior of a `useRef` variable when its value is updated?
What is the primary purpose of the `useRef` hook?

What is the primary purpose of the useRef hook?

Select the correct answer

Which of the following best describes the behavior of a `useRef` variable when its value is updated?

Which of the following best describes the behavior of a useRef variable when its value is updated?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 4
some-alt