Cleanup Functions for Refs
Explore how React 19 improves ref management by enabling cleanup functions directly within ref callbacks. Understand how to attach and remove DOM event listeners in one place, simplifying component logic and preventing memory leaks. Practice common patterns like closing modals on outside clicks and managing event listeners declaratively.
We'll cover the following...
In React, refs are often used to interact directly with DOM elements. While state and props describe the UI declaratively, some cases require imperative access, such as registering event listeners, running animations, or detecting outside clicks. Like other side effects, any listeners or DOM manipulations added via a ref should be cleaned up when the component unmounts.
React 19 introduces a cleaner way to handle this: We can return a cleanup function directly from a ref callback, just like we would from useEffect. This eliminates boilerplate and keeps DOM setup and teardown logic in one place.
Problem with the traditional cleanup
Previously, we used useEffect to attach and clean up things like event listeners or animations. This often splits the setup and teardown logic across different parts of the component, making the code harder to follow.
Line 4: Creates a ref (
divRef) to access the DOM node.Line ...