React Fundamentals

0% completed

Previous
Next
Understanding Refs and the useRef Hook

In React, refs (short for references) allow you to directly reference and interact with DOM elements. With refs, you can step outside the declarative and component-centric approach of React to directly access DOM properties. They are particularly useful when you need to access specific data in a component without causing a re-render.

What is the useRef Hook?

The useRef hook is a versatile and powerful feature that creates a mutable object which persists across renders and can be used to reference and interact with DOM nodes or React components directly.

The useRef hook comes in handy when:

  • You need to directly modify or read a DOM element (e.g., focusing an input, text selection, or media playback).
  • You want to persist a value across renders without triggering re-renders.
  • You need to integrate with third party DOM libraries.

It returns an object with a current property that can hold a value or reference to a DOM element.

const refContainer = useRef(initialValue);

Here:

  • refContainer is the reference object.
  • initialValue is the initial value of the ref.

Examples

  1. We can use the useRef hook to access and manipulate DOM elements. This example will show how focusing an input can be implemented using the hook.
import React, { useRef } from 'react'; export default function FocusInput() { const inputRef = useRef(); const handleFocus = () => { inputRef.current.focus(); }; return ( <div> <input type="text" ref={inputRef} placeholder="Focus me!" /> <button onClick={handleFocus}>Focus Input</button> </div> ); }

In this example:

  • The useRef hook is imported from React.
  • The useRef hook is used to create a reference object, inputRef with an initial value set to null.
  • The handleFocus handler function uses inputRef.current.focus() to call the .focus() method on the input DOM element, causing it to gain focus.
  • The ref prop with the inputRef as a value is attached to the input field.
  • The onClick prop calling the handleFocus handler function is attached to the button.

Output

Image
  1. We can also use the useRef hook when there is a need to store values that change frequently but should not cause re-renders. In this simple timer example, we use the useRef hook to manage the timer ID.
import React, { useRef, useState } from 'react'; export default function Timer() { const [seconds, setSeconds] = useState(0); const timerRef = useRef(); const startTimer = () => { timerRef.current = setInterval(() => { setSeconds((prev) => prev + 1); }, 1000); }; const stopTimer = () => { clearInterval(timerRef.current); }; return ( <div> <p>Time: {seconds}s</p> <button onClick={startTimer}>Start</button> <button onClick={stopTimer}>Stop</button> </div> ); }

In this example:

  • The useRef and useState hooks are imported from react.
  • A state variable of seconds is initialized to 0 with a setter function of setSeconds for updating the seconds state.
  • The timerRef is initialized as a reference using useRef().
  • Inside startTimer, setInterval() is called, which sets up a recurring callback every 1000 milliseconds (1 second). The callback increments the seconds state by 1 every second using setSeconds.
  • The setInterval() function returns a timer ID, which is stored in timerRef.current.
  • Inside stopTimer, clearInterval() is called with the timer ID stored in timerRef.current, which stops the ongoing timer.
  • The component renders:
    • A paragraph (<p>) displaying the current seconds value (the number of seconds elapsed).
    • A "Start" button, which triggers the startTimer function when clicked.
    • A "Stop" button, which triggers the stopTimer function when clicked.

The idea here is to use the timerRef to store the ID of the timer to stop it later without causing re-renders.

Output

Image

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next