Jump to content
Search Community

React, passing array of refs to timeline

isaoBushi test
Moderator Tag

Recommended Posts

Hi again,

 

like in the example when I have many variables I'd like to create an array containing them and pass it to the timeline, instead of listing all the variables inside the tl function, but it triggers the error like in the example. Is it due to something in particular? Some clarification would be appreciated, cheers!

Link to comment
Share on other sites

Hey isao. As CodeSandbox points out, the issue is that you're not listing array as a dependency of the useEffect. But if you add it then it complains about it being changed every render and suggests you put the array in the useEffect. Doing so fixes the issue:

useEffect(() => {
  let array = [bracketEnd, bracketStart];

  gsap.to(array, 100, {
    stagger: 10,
    x: 100,
    fill: "red"
  });
}, []);

Maybe others who work with React more can help you fix this issue in other ways.

  • Like 1
Link to comment
Share on other sites

There are a few approaches that work, but that depends on how the component and it's elements change through it's life cycle. If the component won't change a thing throughout re-renders, then Zach's approach works fine, since the elements will always be there. If for some reason you add/remove elements, then is better to use a callback ref with the useCallback hook in order to  update the DOM elements' references. Keep in mind that useRef won't know of changes in the DOM elements, you have to update the .current property yourself.

 

Finally is always a good idea to kill up your GSAP instances when the component is unmounted, returning a callback in the initial useEffect hook and also storing the GSAP instance with useRef:

const t = useRef(null);

useEffect(() => {
  t.current = gsap.to(...);
  // Now make the component kill the gsap instance when unmounted
  return () => {
    tl.current.kill();
  };
}, []);

Happy Tweening!!!

  • Like 3
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...