Home > Mobile >  React Hooks - useEffect() runs twice because state of a dependency is undefined
React Hooks - useEffect() runs twice because state of a dependency is undefined

Time:04-29

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.

CodePudding user response:

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

CodePudding user response:

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