Home > Software design >  useEffect does not trigger after initial render
useEffect does not trigger after initial render

Time:11-01

I have an array of 16 objects and I use "number" prop to cut unwanted elements. So if I want an array of 8 elements I would type:

<Images number="8"/>

However my useEffect does not run after initial render, but only after I make a change in the array later on, this returns all 16 elements, if I make a typo, wait for a bug screen to render and fix a typo, my browser shows 8 elements as it should. This is the rest of my code:

const Images = (props) => {
    const [deck, setDeck] = useState(data);
    // data.length is equal 16

    const sliceDeck = () => {
        data.splice(parseInt(props.number, 10), data.length)
    }
    
    useEffect(()=>{
        sliceDeck()
        setDeck(data)
    }, [])

    return (
        <>
        <div className="img-container">
           {deck.map(object => <div className="img-on" key={object.id}><img src={object.src} alt=""/></div>)}
        </div>

        </>
    );
  }
  
  export default Images;

CodePudding user response:

You need to add props.number to the dependency array to make sure it runs every time there is an update to it

const Images = (props) => {
    const [deck, setDeck] = useState(data);
    
    useEffect(()=>{
      if(!isNaN(props?.number)){
        const temp = data.splice(parseInt(props?.number, 10), data.length)
        setDeck(temp)
      }
    }, [props?.number])

    return (
        <>
          <div className="img-container">
            {deck.map(object => <div className="img-on" key={object.id}>
              <img src={object.src} alt=""/>
            </div>)}
          </div>
        </>
    );
  }
  
  export default Images;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

emphasized text

  • Related