mouchin777
mouchin777

Reputation: 1588

How to trigger an useEffect if the array is greater than

Im trying to trigger an useEffect, only when my images array is greater than 0. But in the console, I notice that its being triggered twice, when its 0, and greater than 0.

import { useSelector, useDispatch } from 'react-redux';
import { myModules } from '#/redux/modules';

    const Component = () => {
     const images = useSelector(getImages)
     const dispatch = useDispatch();
    
      useEffect( () =>  {
        dispatch(myModules.actions.setMaskVisible(true));
      }, [images.length > 0, dispatch]);
    
    }

How can I make this useEffect work ONLY when images array is greater than 0 ?

Upvotes: 0

Views: 451

Answers (2)

GregMit
GregMit

Reputation: 497

Both of these approach should work

import { useSelector, useDispatch } from 'react-redux';
import { myModules } from '#/redux/modules';

    const Component = () => {
     const images = useSelector(getImages)
     const dispatch = useDispatch();
    
      useEffect( () =>  {
        if (images.length > 0) {
          dispatch(myModules.actions.setMaskVisible(true));
        }
      }, [images, dispatch]);
    
    }

import { useSelector, useDispatch } from 'react-redux';
import { myModules } from '#/redux/modules';

    const Component = () => {
     const images = useSelector(getImages);
     const [triggerEffect, setTriggerEffect] = useState(false);
     const dispatch = useDispatch();
     if (images.length > 0) setTriggerEffect(!triggerEffect);
      useEffect( () =>  {
        dispatch(myModules.actions.setMaskVisible(true));
      }, [triggerEffect, dispatch]);
    
    }

Upvotes: -1

Pranava Mohan
Pranava Mohan

Reputation: 631

This should fix it:

import { useSelector, useDispatch } from 'react-redux';
import { myModules } from '#/redux/modules';

    const Component = () => {
     const images = useSelector(getImages)
     const dispatch = useDispatch();
    
      useEffect( () =>  {
          if (images.length > 0) {
            dispatch(myModules.actions.setMaskVisible(true));
          }
      }, [images, dispatch]);
    
    }

Upvotes: 2

Related Questions