1

I have a custom hook and inside I'm doing this:

useEffect(() => {
  dimensions.forEach(dimension => {
    dimension.filterFunction(...);
  });
}, [ dimensions, endDate, startDate ]);

the problem is that this runs every time because I'm passing a new dimensions array. In the parent if I do const dimensions = useMemo(() => [ dimension ], [ dimension ]) it fixes it. But is there a way I can prevent this from inside my custom hook?

3
  • Is the issue that the useEffect triggers when it is passed the same dimensions array, as in the contents have not changed? Because useEffect cannot perfom equality checks on arrays - you've basically added the equality check in with useMemo, which seems like a reasonable solution. The only other way I can think of is to store the previous value of dimensions and manually check it, which seems like it would be much less elegant. Also, FYI, useEffect is not a custom hook. Commented Mar 5, 2020 at 21:58
  • Can you please clarify "runs every time"? Always runs on render? Commented Mar 5, 2020 at 21:59
  • @LawrenceWitt thanks, I'll check that solution. I know useEffect is not a custom hook. I'm using it inside my custom hook. Commented Mar 5, 2020 at 22:01

1 Answer 1

1

What about passing dimensions as a parameter to a function wrapping your useEffect() and removing it from the array that's the second argument to useEffect?

    const useDimensions = (dimensions) => {
        useEffect(() => {
            dimensions.forEach(dimension => {
                dimension.filterFunction(...);
            });
        }, [ endDate, startDate ]);
    };

That should keep it from re-rendering and you should be able to call it whenever you need to.

Sign up to request clarification or add additional context in comments.

3 Comments

@stackoverflow-newbie Thanks for the edit...it's been a long day.
If later I want to do const dimensions = useDimensions(), shouldn't this return dimensions? thanks for the answer
Sorry, I didn't get an idea of how you're using the results from your code sample.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.