Sitemap

React useRef()

2 min readAug 2, 2025

--

In my react leaning journey I barely use this hook called useRef cause I don’t know what that hook do.

But in recent while I start learning GSAP for that cool animation I use this hook accidently and I get it how this works take a look on my code and a sample video to understand how this hook actualy works…

import React from 'react'
import { gsap } from 'gsap/gsap-core'
import { useGSAP } from '@gsap/react'

const App = () => {

useGSAP(() => {
gsap.to(".box", {
x: 600,
duration: 1,
ease: "power2.inOut"
})
})

return (
<div className='main' >
<div className="box h-80 w-80 bg-red-400 border-2 rounded-3xl flex justify-center align-middle items-center" > Hello I am box</div>
<div className="box h-80 w-80 bg-amber-400 border-2 rounded-3xl flex justify-center align-middle items-center"> Hello I am box</div>
</div>
)
}

export default App
Press enter or click to view image in full size
Without using useRef()

In the above code I make two identical boxes but I only want animation for upper box so what can I do.

Get MagicalDev31’s stories in your inbox

Join Medium for free to get updates from this writer.

I just name other class to that box and run the animation smoothly.
But the problem is what if I have a 100 boxes that is headache ,now so in this case useRef() change the game.

Just take a look at below code:

import React from "react";
import { useRef } from "react";
import { gsap } from "gsap/gsap-core";
import { useGSAP } from "@gsap/react";

const App = () => {
const container = useRef();

useGSAP(() => {
gsap.to(
container.current,
{
x: 600,
duration: 1,
ease: "power2.inOut",
},
{ scope: container }
);
});

return (
<div className="main">
<div
className="box h-80 w-80 bg-red-400 border-2 rounded-3xl flex justify-center align-middle items-center"
ref={container}
>
{" "}
Hello I am box
</div>
<div className="box h-80 w-80 bg-amber-400 border-2 rounded-3xl flex justify-center align-middle items-center">
{" "}
Hello I am box
</div>
</div>
);
};

export default App;
Press enter or click to view image in full size
With useRef( ) property

Now just adding the useRef hook I target the box by adding the ref property to that box and boom the problem solved..

--

--

MagicalDev31
MagicalDev31

Written by MagicalDev31

0 followers

I am a frontend developer. And also a dropout student. I love web dev and I am currently learning animation in frontend developement with GSAP.