Tracking the Cursor with Framer Motion

Interactive websites that respond to user movements feel alive and engaging. One way to achieve this is cursor tracking, where elements react to the position of the mouse. This technique can create 3D tilts, parallax effects, or subtle movements that make your UI feel more dynamic.

In this article, we'll explore how to implement a 3D tilting box using Framer Motion. We'll start by understanding the concept, then dive into step-by-step coding with explanations.

How Cursor Tracking Works

The idea is simple:

  1. Track the cursor’s x and y positions relative to a container.
  2. Store these positions as motion values in Framer Motion.
  3. Map these values to transforms like rotateX, rotateY, or translateZ.
  4. Apply these transforms to your element to make it respond dynamically.

By the end of this tutorial, you'll have a small, reusable cursor-tracking component ready for your React projects.

Step 1: Setting Up the Project

npm install motion

Step 2: Create the Cursor Tracker Component

Create a new file TrackingTheCursor.jsx (or .tsx if using TypeScript).

Here’s the basic structure:

Loading...

Step 3: Understanding the Code

  1. useMotionValue: Creates reactive values for the x and y positions of the cursor. These values can be smoothly animated.
  2. useSpring: Wraps motion values with a spring for smoother movement. It controls how fast and bouncy the animation feels.
  3. useEffect + mousemove:
  • Adds an event listener to track the cursor.
  • Updates mouseX and mouseY whenever the cursor moves.
  • Cleans up the listener when the component unmounts.
  1. motion.div: This is the element that follows the cursor. Its x and y are bound to our spring values. Styling makes it a small semi-transparent circle and ensures it doesn't interfere with pointer events.

🎉 Conclusion

By following these steps, you now have a fully functional cursor-tracking animation using Motion. This small interactive feature can dramatically enhance user engagement and make your website feel modern and dynamic.

Experiment with spring parameters, colors, and sizes to create unique effects that match your website’s style.