Home > front end >  useEffect firing even when dependency array is not true or has not changed
useEffect firing even when dependency array is not true or has not changed

Time:06-23

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

CodePudding user response:

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])
  • Related