DEV Community

Cover image for Beyond Props and State: Understanding and using Refs in React
YogiYiorgos
YogiYiorgos

Posted on

Beyond Props and State: Understanding and using Refs in React

React is a powerful Javascript library for building user interfaces and one of the features it offers is the ability to create and use refs. In this blog post, we'll take a closer look at what refs are, when to use them, and how to create and use them in our React projects.

What are refs in React?

Refs are a way to access a component's underlying DOM (Document Object Model) node. They allow us to access the value of a form element, trigger a focus or media playback, and more. Refs can be created and used in both functional and class components.

When to use refs in React?

Refs should be used sparingly and only when necessary. In general, it's recommended to use state and props to manage the state of our application. However, there are certain cases where refs offer a better solution:

  • Accessing the value of a form element
  • Triggering a focus on a specific element
  • Triggering media playback
  • Integrating with third-party libraries that require direct access to the DOM ## How to create and use refs in React? To create a ref, we can use the useRef hook in functional components or the createRef method in class components. Then, we can attach the ref to any JSX element using the ref attribute.
import { useRef } from 'react';

const MyInput = () => {
  const inputRef = useRef(null);

  function handleSubmit(e) {
    e.preventDefault();
    console.log(inputRef.current.value);
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" ref={inputRef} />
      <button type="submit">Submit</button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the example above, inputRef is a ref created using the useRef hook. It is attached to the input element using the ref attribute. When the form is submitted, the handleSubmit function is called and it logs the current value of the input field by accessing inputRef.current.value.

We can also use refs for other purposes such as triggering a focus on a specific element, or triggering media playback.

import { useRef } from 'react';

const MyVideoPlayer = () => {
  const videoRef = useRef(null);

  function handlePlay() {
    videoRef.current.play();
  }

  return (
    <div>
      <video ref={videoRef}>
        <source src="my-video.mp4" type="video/mp4" />
      </video>
      <button onClick={handlePlay}>Play</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In the example above shows how refs can be very useful, where videoRef is a ref created using the useRef hook and it is attached to the video element using the ref attribute. When the play button is clicked, the handlePlay function is called and it triggers the play method on the video element by accessing videoRef.current.play().

What makes refs so different?

Now that we have covered the basics of hoe to create and use refs in a React application, let's delve deeper into some of the key features and considerations when utilizing refs.

Refs have a few key differences form state and props that make them useful is certain situations. One important difference is that refs persist across re-renderes, unlike regular variables which reset in every render. This makes refs useful for storing information that needs to be accessed between renders, such as the current position of a video player or the scroll position of a container.

Another difference is that changing a ref does not trigger a re-render, unlike state variables which, when they change, they trigger a re-render. This can be beneficial in situations where we need to update a value without causing a re-render, such as when updating the position of an element on a drag and drop interaction.

Finally, refs are local to each copy of a component, unlike variables outside of the component which are shared. This means that each instance of a component can have its own ref, which can be useful in situations where multiple instances of a component need to maintain their own state independently.

Summary

In summary, refs in React offer a way to access the underlying DOM of a component, providing more control over our application. While it may be tempting to rely on refs for everything, it's important to remember that they should be used when other methods such as props and state are not sufficient. Used correctly, refs can be a powerful tool in our React arsenal.

Top comments (0)