Search code examples
reactjsuse-effect

useEffect with dependency array triggers multiple times because of array.map


I'm creating a simple React application where a parent component renders a number of children components based on an input range slider (using array.map).

I'm performing certain actions within a useEffect with a dependency array in the child component (particularly, I'm obtaining a 3D model's bounding box size using react-three-fiber). Even though I have the dependency array, I can see from the console logs that the useEffect executes each time I move the slider.

How can I ensure that this useEffect only executes once? I was considering passing the useRef of the model to the parent and doing the useEffect actions there, but I'm curious if there's a way to modify useEffect such that it just executes once.


Solution

  • After a deep understanding of my needs, one of the arguments was changing.

    Functions not through a useCallback will always change. Rebuilt objects (and to some extent, arrays) are new as well (unless memoized).

    I checked what is changing first. Instead of using useRef, figure out what is changing in the data.

    But in reality, if that dependency was actually needed, I can memoize it (e.g. useMemo) instead of just removing it.