Jump to content
Search Community

Is using useLayoutEffect some sort of last resort for gsap if animation doesn't work as expected

Jun Xiang test
Moderator Tag

Go to solution Solved by Rodrigo,

Recommended Posts

I used gsap.fromto animate a component when it is rendered through a conditional statement

something like below:

 
const [openComponent, setOpenComponent] = useState(false);

<button onClick={_=>setOpenComponent(true)}>Open</button>

return {openComponent && <Component/>}

 

and in the Component.jsI used useEffectto render the animation

useEffect(_ => {
      gsap.set(ref.current, { y: 0 });
      gsap.from(ref.current, {
          y: "-100%",
          duration: 0.5,
          ease: "expo.out",
      });
}, []);

However, the Componentsometimes rendered in its original position (y=0) before starting the animation. It means you will see a flick of the component before the animation starts.

When I changed useEffectto useLayoutEffect, it doesn't happen.

I have another component called Loading which uses a similar logic as above and the flick doesn't happen. I went through the forum and found this post

It is true that the Component has a React.fragment (Loading doesn't have React.fragment)but when I removed it, the flick still happens unless I use useLayoutEffect.

Another difference of the Loading from the Component is that Loading is less complicated.

Component structure:

<div>
  <div>
  	<div>
  	  <p></p>
      <div>
        <span></span>
        <span></span>
      </div>
	</div>
      <div>
        <p></p>
      </div>
      <div>
          <p></p>
      </div>
    </div>
  </div>

Loading structure:

<div>
  <img/>
</div>

Here is a video example (Ignore the watermark😅)

 

I am not familiar with codepen or any other online editors to code a React in it and make an example. Sorry for the inconvenience. 😁😅

Link to comment
Share on other sites

  • Solution

Hi,

 

I wouldn't call useLayoutEffect a last resource kind of thing, is just a tool provided by React for certain scenarios. In this cases I don't use .from() instances, which undoubtedly are very convenient, and just create the initial state using CSS and then use a regular .to() instance to avoid that initial render, specially with modals, alerts, toasts and/or whatever other name they have ;).

 

Now if useLayoutEffect is working as you expect, then you have your solution!!! If it ain't broken don't fix it, some people would say :D

 

Happy Tweening!!!

  • Like 4
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...