Pushing the limit of useState and useEffect to the NEXT level
Manoj Shrestha
MERN Stack Developer but Industry turned me into Next.js Developer | PostgreSQL | PrismaORM | ReactQuery | NextAuth/AuthJS
Look, we have already understood the fundamentals of useState and useEffect and how they are used. Today, we will push the limit. With the following code, you will be able to create an object (a square) that moves along with the mouse.
import React, { useState } from 'react';
const DraggableBox = () => {
const [position, setPosition] = useState({ x: 0, y: 0 });
const [isDragging, setIsDragging] = useState(false);
const [offset, setOffset] = useState({ x: 0, y: 0 });
const handleMouseDown = (e) => {
setIsDragging(true);
setOffset({
x: e.clientX - position.x,
y: e.clientY - position.y,
});
};
const handleMouseUp = () => {
setIsDragging(false);
};
const handleMouseMove = (e) => {
if (isDragging) {
setPosition({
x: e.clientX - offset.x,
y: e.clientY - offset.y,
});
}
};
return (
<div
className="draggable-container"
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseMove={handleMouseMove}
>
<div
className="draggable-box"
style={{ transform: `translate(${position.x}px, ${position.y}px)` }}
>
Drag me!
</div>
</div>
);
};
export default DraggableBox;
This example uses React hooks (useState) to manage the position of the draggable box. It listens to mouse events (onMouseDown, onMouseUp, and onMouseMove) to update the position of the box based on the mouse movements.
Remember to add appropriate CSS styles to make the box look and behave as desired. This is a basic example, and for a more complex application, you might want to consider using libraries like React DnD (Drag and Drop) for better functionality and a smoother user experience.
Conclusion
Practice this to learn the use of useState in a better way.