Advanced React

Understand Refs, Portals, Error Boundaries, and Higher-Order Components in React.

Advanced React Concepts (Refs, Portals, Error Boundaries, HOCs)

As you become more comfortable with React, you will encounter situations where basic features such as components, props, and state are not enough. React provides several advanced concepts to solve these real-world problems while keeping applications organized and reliable.

Some of the most useful advanced concepts are:

  • Refs
  • Portals
  • Error Boundaries
  • Higher-Order Components (HOCs)

You may not use these features in every project, but understanding them will help you build more professional React applications.

Refs

A Ref (Reference) allows you to directly access a DOM element or store a value without causing a component to re-render.

Normally, React updates the user interface through state. However, some tasks require direct access to an element, such as focusing an input field or playing a video.

Example

jsx
import { useRef } from "react";

function App() {
  const inputRef = useRef();

  function focusInput() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={focusInput}>
        Focus Input
      </button>
    </>
  );
}

Explanation

  • useRef() creates a reference.
  • The ref attribute connects the reference to the input.
  • Clicking the button places the cursor inside the input field.

Common Uses of Refs

  • Focusing input fields
  • Playing videos
  • Scrolling to an element
  • Accessing DOM elements
  • Storing values that should not trigger a re-render

Portals

Normally, React renders components inside their parent component.

Sometimes you need to display content outside of the normal component hierarchy.

This is where Portals are useful.

Portals allow React components to render somewhere else in the HTML document.

Real-World Example

Imagine opening a popup window.

Even though the popup belongs to a page component, it usually appears above the entire webpage.

React Portals make this possible.

Example

jsx
import ReactDOM from "react-dom";

function Modal() {
  return ReactDOM.createPortal(
    <h2>This is a popup!</h2>,
    document.getElementById("modal-root")
  );
}

Common Uses

  • Modal windows
  • Popups
  • Notifications
  • Tooltips
  • Floating menus

Portals help ensure these elements appear in the correct position on the page.

Error Boundaries

Sometimes an unexpected error occurs inside a component.

Without protection, the entire React application may stop working.

Error Boundaries help catch rendering errors and display a fallback user interface instead of crashing the whole application.

Example

jsx
class ErrorBoundary extends React.Component {
  componentDidCatch(error) {
    console.log(error);
  }

  render() {
    return this.props.children;
  }
}

Real-World Example

Imagine an online shopping website.

If the Product Reviews section fails to load because of an unexpected error, you do not want the entire website to stop working.

Instead, an Error Boundary can display a friendly message such as:

text
Something went wrong.
Please try again later.

This creates a much better user experience.

Note: Error Boundaries are currently implemented using class components. Even in modern React projects that mostly use functional components, you may still encounter Error Boundaries written as classes.

Higher-Order Components (HOCs)

A Higher-Order Component (HOC) is a function that takes one component and returns a new component with additional functionality.

Instead of modifying the original component, the HOC wraps it and adds extra behavior.

Simple Example

jsx
function withGreeting(Component) {
  return function () {
    return (
      <>
        <h2>Welcome!</h2>
        <Component />
      </>
    );
  };
}

If you wrap another component with withGreeting, the greeting appears automatically before the original component.

Common Uses of HOCs

  • Authentication
  • Logging
  • Permissions
  • Analytics
  • Reusable functionality

Although Hooks are now preferred for sharing logic in many situations, you may still encounter HOCs in existing React codebases.

Comparing These Concepts

text
Concept              Purpose
Refs                 Access DOM elements or store values without re-rendering.
Portals              Render components outside the normal component tree.
Error Boundaries     Catch rendering errors and display a fallback UI.
HOCs                 Reuse functionality by wrapping components.

Each feature solves a different problem and is useful in specific scenarios.

Real-World Example

Imagine you are building an online shopping website.

  • Use a Ref to automatically focus the search box when the page loads.
  • Use a Portal to display the checkout popup above the entire page.
  • Use an Error Boundary to prevent the whole application from crashing if the product review section fails.
  • Use an HOC to ensure that only logged-in users can access the checkout page.

Together, these advanced concepts help create a more reliable and user-friendly application.

Best Practices

When using advanced React features:

  • Use Refs only when direct DOM access is necessary.
  • Use Portals for modals, popups, and floating UI elements.
  • Wrap important sections with Error Boundaries to improve reliability.
  • Prefer custom Hooks for sharing logic in modern React, but understand HOCs because they are still used in many existing projects.
  • Keep advanced features simple and focused on solving specific problems.

Summary

Advanced React concepts provide solutions for situations that go beyond basic components and state management. Refs allow direct interaction with DOM elements, Portals render components outside the normal hierarchy, Error Boundaries protect applications from rendering errors, and Higher-Order Components add reusable functionality to existing components. While beginners may not use these features every day, understanding them prepares you to work with larger React projects and existing production codebases.

Key Takeaways

  • Refs provide direct access to DOM elements and persistent values.
  • useRef is commonly used to focus inputs, scroll elements, or interact with the DOM.
  • Portals render components outside the normal React component hierarchy.
  • Portals are ideal for modals, tooltips, and popup windows.
  • Error Boundaries catch rendering errors and prevent the entire application from crashing.
  • Error Boundaries are currently implemented using class components.
  • Higher-Order Components (HOCs) wrap components to add reusable functionality.
  • Understanding these advanced concepts helps you build more reliable, scalable, and professional React applications.
Let's learn with DevBrainBox AI