'React Hooks - useEffect() runs twice because state of a dependency is undefined

In the below code, the second useEffect() is run twice - once when employee is undefined, and once again when employee has a value.

  const [employee, setEmployee] = useState<Employee | undefined>(undefined);
  const [buttonDisabled, disableButton] = useState<boolean>(true);

  useEffect(() => {
    // Run some fetch requests and then set employee state
    setEmployee(employee);
  }, []);

  useEffect(() => {
    const employeeId = employee.Id;
    // Run some fetch requests and then set buttonDisabled state
    disableButton(false);

    // buttonDisabled is passed to a child component as a prop.

  }, [employee]);

How do I make sure the second useEffect() is only run once and only when employee has a value.



Solution 1:[1]

const [employee, setEmployee] = useState<Employee | undefined>(undefined);
const [buttonDisabled, disableButton] = useState<boolean>(true);

  useEffect(() => {
    // Run some fetch requests and then set employee state
    setEmployee(employee);
  }, []);

  useEffect(() => {
    if (employee) {
       const employeeId = employee.Id;
       // Run some fetch requests and then set buttonDisabled state
       disableButton(false);

       // buttonDisabled is passed to a child component as a prop.
    }


  }, [employee]);

Solution 2:[2]

return when employee is undefined , like this

const [employee, setEmployee] = useState<Employee | undefined>(undefined);
  const [buttonDisabled, disableButton] = useState<boolean>(true);

  useEffect(() => {
    // Run some fetch requests and then set employee state
    setEmployee(employee);
  }, []);

  useEffect(() => {
    if(!employee)return;
    const employeeId = employee.Id;
    // Run some fetch requests and then set buttonDisabled state
    disableButton(false);

    // buttonDisabled is passed to a child component as a prop.

  }, [employee]);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KnowYourElements
Solution 2 Hritik Sharma