DEV Community

Cover image for Understanding forwardRef in React: A Comprehensive Guide
Pratik Singh
Pratik Singh

Posted on

2

Understanding forwardRef in React: A Comprehensive Guide

As React continues to evolve, developers often encounter patterns that enhance the flexibility and usability of components. One such pattern is forwardRef, a powerful feature that allows components to pass refs to their children, enabling direct access to the underlying DOM elements or component instances. In this blog, we’ll explore what forwardRef is, when to use it, and how it can streamline your React applications.

What is forwardRef?

forwardRef is a higher-order component that enables you to create a ref that can be forwarded to a child component. This is particularly useful when you want a parent component to directly interact with a child component’s DOM node, especially in cases where you need to manage focus, animations, or integrate with third-party libraries that rely on refs.

Why Use forwardRef?

Using forwardRef offers several advantages:

  1. Direct DOM Manipulation: It allows parent components to manipulate the DOM of child components directly.
  2. Integration with Third-Party Libraries: Many libraries expect refs to be passed to components, and forwardRef makes this seamless.
  3. Reusable Components: It helps maintain encapsulation while exposing necessary functionalities to parent components, enhancing reusability.

Syntax Overview

The syntax for forwardRef is straightforward. Here’s how it looks:

const ComponentWithRef = React.forwardRef((props, ref) => {
  return <div ref={ref}>Hello, World!</div>;
});
Enter fullscreen mode Exit fullscreen mode

In this example, ref is passed to the underlying <div>, allowing the parent component to access it.

Implementation Example:

Let’s look at a practical example to understand how to use forwardRef.

import React, { useRef } from 'react';

const CustomInput = React.forwardRef((props, ref) => {
  return <input ref={ref} {...props} />;
});

const ParentComponent = () => {
  const inputRef = useRef();

  const focusInput = () => {
    inputRef.current.focus(); // Directly focuses the input element
  };

  return (
    <>
      <CustomInput ref={inputRef} placeholder="Type here" />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
};

export default ParentComponent;
Enter fullscreen mode Exit fullscreen mode

Explanation:

CustomInput: This is a functional component that uses forwardRef to forward its ref to the underlying <input> element.

ParentComponent:: This component uses the useRef hook to create a reference (inputRef). When the button is clicked, it calls focusInput, which directly focuses the input field.

What Happens Without forwardRef?

If you create a component without using forwardRef, you’ll encounter certain limitations. Here’s an example to illustrate this:

import React, { useRef } from 'react';

const CustomInput = ({ placeholder }) => {
  return <input placeholder={placeholder} />;
};

const ParentComponent = () => {
  const inputRef = useRef();

  const focusInput = () => {
    // This will NOT work
    inputRef.current.focus(); // Will throw an error
  };

  return (
    <>
      <CustomInput ref={inputRef} placeholder="Type here" />
      <button onClick={focusInput}>Focus Input</button>
    </>
  );
};

export default ParentComponent;
Enter fullscreen mode Exit fullscreen mode

Implications of Not Using forwardRef:

  1. Limited Access: You won’t have direct access to the input's DOM node, making tasks like focusing the input impossible. 2.** Increased Complexity**: You may need to pass props through multiple layers of components, leading to prop drilling.
  2. Reduced Reusability: The component becomes less flexible and harder to integrate with libraries requiring refs.
  3. Performance Considerations: Using forwardRef can enhance performance in scenarios requiring direct DOM access. By leveraging refs, you can avoid unnecessary re-renders and maintain a clean component tree, leading to improved application performance.

Conclusion

forwardRef is an essential tool in the React developer's toolkit, enabling the creation of flexible, reusable components. By allowing direct access to DOM nodes and facilitating integration with third-party libraries, it enhances component architecture. Embracing forwardRef can lead to cleaner code and improved functionality in your applications. As you continue to build with React, remember to leverage this powerful feature for optimal component design!

Build gen AI apps that run anywhere with MongoDB Atlas

Build gen AI apps that run anywhere with MongoDB Atlas

MongoDB Atlas bundles vector search and a flexible document model so developers can build, scale, and run gen AI apps without juggling multiple databases. From LLM to semantic search, Atlas streamlines AI architecture. Start free today.

Start Free

Top comments (0)

Scale globally with MongoDB Atlas. Try free.

Scale globally with MongoDB Atlas. Try free.

MongoDB Atlas is the global, multi-cloud database for modern apps trusted by developers and enterprises to build, scale, and run cutting-edge applications, with automated scaling, built-in security, and 125+ cloud regions.

Learn More

👋 Kindness is contagious

Dive into this insightful article, celebrated by the caring DEV Community. Programmers from all walks of life are invited to share and expand our collective wisdom.

A simple thank-you can make someone’s day—drop your kudos in the comments!

On DEV, spreading knowledge paves the way and strengthens our community ties. If this piece helped you, a brief note of appreciation to the author truly counts.

Let’s Go!