Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useEffect firing even when dependency array is not true or has not changed

I hava a simple component

import React, { useState, useEffect } from 'react';
import { HousesType } from '@src/store';

export const Home = () => {
  const [houses, setHouses] = useState<HousesType[]>([]);

  useEffect(() => {
    console.log('Should it fire if properties has no length?');
  }, [houses.length])


  return <h1>Testing</h1>
}

For some reason when I render home, I get the console log even thou the houses array has no length

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

as someone said it will fire on first render, when the properties is initialized, but to avoid doing something whether properties.length isn’t less than 1 then put your logic inside if condition :

useEffect(() => {
    if (!properties?.length) {
      console.log('Should it fire if properties has no length?');
    }
  }, [properties.length])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading