Finding a use for React ref callbacks
When you want to reach into the DOM in your React components most likely you do that by using React’s ref API. React offers two ways to use them, one is by creating refs manually in the constructor while the other is passing a callback function that receives the underlying DOM element. By using this second method in this article I’ll demonstrate a couple of uses that can come in handy for any React developer.
Callback that is passed to ref prop on any native HTML element will receive the same element as an argument. React guarantees that the callback is called once the element is inserted into the DOM and before componentDidMount and componentDidUpdate lifecycle hooks. Also, the callback will be fired right before the element is removed from the DOM with null as its argument. With those facts, it becomes clear that ref callback is perfect when you need to manipulate the DOM or utilize some third-party library that doesn’t play well with React.
If, for example, we have an app that at the bottom of the screen has ‘Load More’ button that will load the next 10 items. And we want the scroll state to be at the top of the new elements once loaded, we can defer that logic to the ref callback:
As soon as the element for the first item on the next page is painted on the screen React will call the callback and screen will smoothly scroll to that element. In contrast, another solution for this problem is more complex, which includes fetching the exact element from the DOM in componentDidUpdate while also checking the state and/or props for certain changes.
Working with the third party animation library can also be simplified by using ref callbacks:
As mentioned, React will call the callback after the element is inserted into the DOM and in this case in time to animate the element by adding a CSS class to it. Again without writing custom behavior for lifecycle hooks or reaching into the DOM ourselves.
In certain cases, you’ll need to access DOM elements form child components or you’ll need to access the root element of a stateless (functional) child component, for which ref API can’t be used on. The next example will show how to do that with passing the function to a prop:
When ChildComponent is inserted into the DOM the parent will have the reference to the root node of the stateless component and so any operation needed on that HTML element can be done from the parent’s scope.
React refs callbacks are a very useful tool when you need to perform one-time action on DOM elements without the need to resort to handling component state, lifecycle hooks, or fetching the element by querying the DOM. Since callbacks are functions they can be extracted to a separate module and that way become a reusable piece of the application.