DEV Community

Cover image for React: Custom Cursor (No Extra dependencies!)

React: Custom Cursor (No Extra dependencies!)

Rahul on March 09, 2021

Just like the last article, this also focuses on a feature that I would like my portfolio to have. A custom cursor. I've noticed this treat a lot l...
Collapse
 
ivan_jrmc profile image
Ivan Jeremic

the cursor cannot work in a complex layout because of the re-renders, each time you move the mouse all components re-render and the mouse starts lagging in a complex application.

Collapse
 
harshal255 profile image
Harshal Kahar

same problem brother, have you solved this problem??

Collapse
 
louislecout profile image
Louis Lecouturier

Do you have any solution that may fix this problem ?

Collapse
 
ivan_jrmc profile image
Ivan Jeremic • Edited

Don't use context like this example does. I would solve this with some atomic state library outside react like jotai or recoil, valtio works too.

Collapse
 
chiubaca profile image
Alex Chiu

Nice, I like this a lot! Did you notice some janky behaviour when using the delayed animation? re: transition-duration: 100ms;

Collapse
 
holdmypotion profile image
Rahul

Thank you so much :)
I did. It does sometimes lag on the initial paint. I'll try to update the blog if I find a solution for that. Do you have something in mind?

Collapse
 
chiubaca profile image
Alex Chiu

Yeah i was tinkering with the same effect but using refs instead:

 const cursorRef = React.useRef<HTMLDivElement>(null!);

const moveListener = React.useCallback((event) => {
    const { clientX, clientY, target } = event;

    if (target === 'target-id'){
      // some custom logic to change cursor icon in here
    } 

    const mouseX = clientX - cursorRef.current.clientWidth / 2;
    const mouseY = clientY - cursorRef.current.clientHeight / 2;

})

return <div  className='custom-cursor' ref={cursorRef} /></div>;
Enter fullscreen mode Exit fullscreen mode

I dont get the lag with this method, but i'm hitting a bug with css animations when doing this method πŸ˜•

Thread Thread
 
abhinavjha27 profile image
ABHINAV JHA

is it in the hooks file

Collapse
 
stereobooster profile image
stereobooster
.custom-cursor {
  cursor: url('path-to-image.svg'), auto;   
}
Enter fullscreen mode Exit fullscreen mode

?

Collapse
 
faysalshuvo profile image
Faysal Shuvo

Awesome article; but the hover effect does not work. what can I do to make I work?

Collapse
 
holdmypotion profile image
Rahul

Thank you!
I just checked the code again. It should work, you can try to compare your code with this codesandbox.io/s/competent-hodgkin...

Hope you get it sorted :)

Collapse
 
frommainland profile image
frommainland

Thanks for the detailed walk through.