In the official React definition “Refs provide a way to access DOM nodes or React elements created in the render method”.
In this article I will show you how Refs can be used for other purposes.
I will not dwell on the explanation of the concept or the various methods of creating refs. You can find all this on the following link: https://reactjs.org/docs/refs-and-the-dom.html
Standard use case
In a common scenario we can use refs like this:
In this case, ref is used as a reference to a DOM Input.
inputRef allow us access to input properties like value.
Advanced use — Timeout
The next example is a simple notice component. The notice can be closed by clicking a button, otherwise it will automatically close after a time limit.
In this case the ref is used to store a mutable data: the timeout ID
The steps are:
Create the ref (line 6)
Assign the timeout value to ref (line 18)
-
Clear timeout:
- If notice is closed by the user (line 13)
- When component is unmounted (line 21)
Advanced use #2— RequestAnimationFrame
The next example is a simple component that renders a div with an animation on the height.
In this example 3 refs was created:
divRef: A classical use of refs. I’ts a reference to the Div element below.
requestRef: It contains the requestAnimationFrame id
heightRef: It contains the updated height value
The animate function is called until heightRef.current reaches the value of HEIGHT_LIMIT. heightRef.current is incremented by 1 each time the function is called.
If the component will be unmounted before heightRef.current reaches the value of HEIGHT_LIMIT, cancelAnimationFrame function will be executed
Advanced use #3 — Custom Hook
The next example creates a hook that returns a ref containing the x, y position of the mouse. With the help of the requestAnimationFrame a rounded div is animated to follow the mouse
The usePosition hook adds a mouseMove event to the window and stores the clientX and clientY values.
In the animate function of the Point component the values x and y are used to animate the top and left properties of the div referenced by pointRef
Conclusion
React refs are extremely useful for saving mutable data without triggering a re-render of the component.
They are powerful even when used in custom hooks and guarantee high performance.
Discussion (3)
Thanks for sharing :)
Your avanced axample is the same as the first one, thank you anyway!
Thank you for letting me know. I fixed the mistake!