Home > front end >  How to trigger an useEffect if the array is greater than
How to trigger an useEffect if the array is greater than

Time:10-02

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 ?

CodePudding user response:

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]);
    
    }

CodePudding user response:

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]);
    
    }

  • Related