Search code examples
reactjsreact-nativereact-reduxreact-hooksuse-effect

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

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