Getting started

🤙 React UseGesture is a set of hooks that let you bind mouse and touch events to any React component.

With the data you receive, it becomes easy to set up complex gestures like dragging and pinching with a few lines of code. You can use this library stand-alone, but to make the most of it you should combine it with an animation library like React-spring.


Using yarn:

yarn add react-use-gesture

Using npm:

npm install --save react-use-gesture

Simple example

The following example makes a <div/> draggable so that it follows your mouse or finger on drag, and returns to its initial position on release.

import { useSpring, animated } from '@react-spring/web'
import { useDrag } from 'react-use-gesture'
function PullRelease() {
const [{ x, y }, api] = useSpring(() => ({ x: 0, y: 0 }))
// Set the drag hook and define component movement based on gesture data
const bind = useDrag(({ down, movement: [mx, my] }) => {
api.start({ x: down ? mx : 0, y: down ? my : 0 })
// Bind it to a component
return <animated.div {...bind()} style={{ x, y }} />

How does this work?

The useDrag hook returns a function (stored in the bind constant), which when called returns an object with event handlers. Here, when you spread {...bind()} into a component, you're actually adding onMouseDown and onTouchStart event handlers.

It's important that you understand 👊 React UseGesture is not responsible for actually moving the component. The useDrag hook just hands over gesture data to React-spring which sets the component transforms. If you're not familiar with React-spring, head over its documentation here.