0

I'm trying to run a function on a context using useEffect, but after the component mounts. Otherwise the function runs as the context is first loaded in, and gives a bad result. I'd love to nest a useEffect inside another useEffect that runs after load, but I cant. How do I trigger the useEffect to wait until componentDidLoad to run? Do I need to revert my functional component to a class function?

Here is the effect im running

  useEffect(() => {
    let count = Object.keys(context).filter((x) => context[x] !== "").length;
    numChange = count;
  }, [context]); <=== run AFTER the original update of the context

To clarify. The context is an object, and I count how many of the objects properties have values. As the context is initially counted (let's say 5 out of the 10 properties already had values), the "number === 5". But what I want to do is count the changes after the initial amount of properties with values in the context when the component mounts. So if n = 5, I want to count any property that gets a value after n.

IWI
  • 1,528
  • 4
  • 27
  • 47

1 Answers1

3

When your useEffect has a dependency and you want to act it like a componentDidMount, adding a ref check is enough:

const isMounted = useRef(false);

useEffect(() => {
  if (!isMounted.current) {
    let numChange = Object.keys(context).filter((x) => context[x] !== "")
      .length;
    setState(numChange);
    isMounted.current = true;
  }
}, [context]);

See use cases of useEffect for more context and examples.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • This works, but I think because one of my values is coming in from an API call, the count is 1 (instead of 5). Maybe I need an await or something. – IWI Dec 02 '20 at 18:17