React TS useRef() hook

This hook is useful when we are trying to read some input field or when we just need the reference to the element for getting size or other properties.

How to use it?

imagine we are trying to make a tooltip under some element when user hovers over it

  • make ButtonTooltip component with props tooltipText and children
  • create variable that holds the reference-buttonRef
  • link the buttonRef to the button via the ref prop
  • add onMouseEnter and onMouseLeave
  • in logic for handling mouse enter reference it, and get the properties you need
import React, { useRef } from 'react'

function ButtonTooltip({ tooltipText, children }: { tooltipText: string, children: React.ReactNode }) {
    const buttonRef = useRef<HTMLButtonElement | null>(null);

    const handleMouseEnter = () => {
        if (buttonRef.current) {
            const buttonRect = buttonRef.current.getBoundingClientRect();
            const tooltip = document.createElement('div');
            tooltip.className = 'tooltip';
            tooltip.textContent = tooltipText;
   = 'absolute';
   = buttonRect.left + 'px';
   = buttonRect.bottom + 'px';

    const handleMouseLeave = () => {
        const tooltip = document.querySelector('.tooltip');
        if (tooltip) {

    return (


export default ButtonTooltip

and now we can use it in our app

function App() {

  return (
    <div className="App" style={
      // center of the screen
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh'
      <ButtonTooltip tooltipText="Tooltip text" >
        Hover me

export default App;

I hope that this simple tutorial did explain the possible use case of useRef() hook.
Happy coding



Leave a Reply

Your email address will not be published. Required fields are marked *