3

What's the way to pass a useRef to a custom hook? I'm creating a custom hook to trigger an animation when the user reaches a section with react-intersection-observer and if the user passes more than one the animation doesn't happen again.

If i pass the ref like this: useAnimation parameters: const useAnimation = (customRef) and the setView method from react-intersection-observer like this: const { ref: customRef, inView: elementIsVisible } = useInView(); i get Parsing error: Identifier 'customRef' has already been declared. If i delete the ref: it happens the same thing.

If i console.log the customRef parameter i get current: undefined

Here is the full code: useAnimation:

import React, { useEffect, useState, useRef, useContext } from "react";
import { DisableAnimationContext } from "../context/disableAnimationContext";
import { useInView } from "react-intersection-observer";

const useAnimation = (customRef) => {
  const { setdisableAnimation } = useContext(DisableAnimationContext);
  const { ref: customRef, inView: elementIsVisible } = useInView();
  const [animationHappened, setAnimationHappened] = useState(false);
  const [animationCounter, setAnimationCounter] = useState({
    counter: 0,
  });

  useEffect(() => {
    if (elementIsVisible) {
      setdisableAnimation(true);
      var currentState = animationCounter.counter;
      setAnimationCounter({
        ...animationCounter,
        counter: (currentState += 1),
      });
    }
    if (animationCounter.counter > 0) {
      setAnimationHappened(true);
    }
  }, [elementIsVisible]);
  return { elementIsVisible, animationHappened };
};

export default useAnimation;

Here is how i call the custom hook in a component:

import React, { useRef, useContext } from "react";
import useAnimation from "../../../hooks/useAnimation";
const aboutRef = useRef();
  console.log(aboutRef);
  const { elementIsVisible, animationHappened } = useAnimation(aboutRef);
Mat
  • 119
  • 1
  • 11

0 Answers0