Creating an Interactive Elastic Cursor with React and GSAP
Introduction
In modern UI design, subtle interactions can significantly improve user experience. One such effect is a custom animated cursor, which provides a more dynamic feel to mouse movements. In this blog, we’ll break down an Elastic Cursor component built with React, GSAP (GreenSock Animation Platform), and TypeScript.
This component enhances cursor movement with a jelly-like animation effect, responding to user interactions smoothly. Let’s dive into how it works and the thought process behind it.
How the Elastic Cursor Works
The ElasticCursor
component is designed to follow the user’s mouse movements while dynamically adapting its shape and size. Key features include:
- Smooth elastic movement using GSAP animations.
- Size and rotation adjustments based on cursor velocity.
- Hover effects that dynamically resize and reposition the cursor.
- Mobile detection to disable the effect on small screens.
Breaking Down the Code
1. Setting Up State and References
1 | const jellyRef = useRef<HTMLDivElement>(null); |
jellyRef
: A reference to the cursor element.isHovering
: Tracks whether the cursor is hovering over an interactive element.x, y
: Mouse coordinates obtained from a custom hook.isMobile
: A media query to disable the effect on smaller screens.
2. Handling Cursor Movement with GSAP
1 | useLayoutEffect(() => { |
GSAP’s quickSetter
is used to optimize animation updates by directly modifying element properties, improving performance.
3. Animating the Cursor with Elastic Motion
1 | const loop = useCallback(() => { |
- Calculates rotation and scale based on cursor velocity.
- Applies transformations dynamically when not hovering.
- Resets rotation when hovering over interactive elements.
4. Handling Hover Effects
1 | const setFromEvent = (e: MouseEvent) => { |
- Detects if the cursor is hovering over an interactive element.
- Expands and moves the cursor over the element.
- Restores default size when no hover is detected.
5. Preventing Animations on Mobile
1 | if (isMobile) return null; |
If the device width is below 768px
, the cursor effect is disabled to maintain usability on touch devices.
6. Rendering the Cursor UI
1 | return ( |
- The primary
div
acts as the elastic cursor. - The secondary
div
creates a smooth tracking effect.
Final Thoughts
The ElasticCursor
component creates a highly interactive experience that enhances the visual appeal of web applications. By leveraging GSAP animations, event listeners, and React hooks, this component seamlessly reacts to user input, making the UI feel modern and responsive.
Potential Enhancements:
✅ Custom colors & themes 🎨
✅ More interactive animations ✨
✅ Support for click-based interactions 🖱️
Try implementing this in your project and let me know what creative modifications you make! 🚀