skip to Main Content
const [employeeListUpdated, setEmployeeListUpdated] = useState(false);

const useAllEmployees = () => {
    const [employees, setEmployees] = useState([]);

    useEffect(() => {
      const fetchEmployees = async () => {
        try {
          const response = await axios.get(API_URL, {
            headers: {
              Authorization: `${bearerToken}`,
            },
          });
          console.log(response);
          setEmployees(response.data);
        } catch (error) {
          console.error("Failed to make request: ", error.message);
        }
      };
      fetchEmployees();
    }, [employeeListUpdated]);

    const employeesWithBlood = employees.map((x) => ({
      ...x,
      blood: bloods[x.bloodId - 1]?.title,
      relation: relations[x.relationxId - 1]?.title,
    }));

    return employeesWithBlood;
  };

I am trying to fetch the employees whenever the value of "employeeListUpdated" gets changed. The value of "employeeListUpdated" gets changed whenever I edit, delete, or add new employee to the database. Here I am using "employeeListUpdated" to keep my employees list up to date. But i am getting one warning "React Hook useEffect has an unnecessary dependency: ’employeeListUpdated’. Either exclude it or remove the dependency array. Outer scope values like ’employeeListUpdated’ aren’t valid dependencies because mutating them doesn’t re-render the component react-hooks/exhaustive-deps". How i can solve this.

3

Answers


  1. As the error says, you can’t use a state outside of the React Hook function.

    The repair solution is as follows

    
    const useAllEmployees = () => {
        // move to here ✅
        const [employeeListUpdated, setEmployeeListUpdated] = useState(false);
        const [employees, setEmployees] = useState([]);
        useEffect(() => {
          const fetchEmployees = async () => {
            try {
              const response = await axios.get(API_URL, {
                headers: {
                  Authorization: `${bearerToken}`,
                },
              });
              console.log(response);
              setEmployees(response.data);
            } catch (error) {
              console.error("Failed to make request: ", error.message);
            }
          };
          fetchEmployees();
        }, [employeeListUpdated]);
    
        const employeesWithBlood = employees.map((x) => ({
          ...x,
          blood: bloods[x.bloodId - 1]?.title,
          relation: relations[x.relationxId - 1]?.title,
        }));
    
        return employeesWithBlood;
      };
    
    Login or Signup to reply.
  2. A couple red flags I can spot with the little context provided:

    1. This line needs to live inside of your custom hook: const [employeeListUpdated, setEmployeeListUpdated] = useState(false);
    const useAllEmployees = () => {
      const [employeeListUpdated, setEmployeeListUpdated] = useState(false);
      // rest your of code...
    };
    
    1. Given that you fix Point 1, nothing in your custom hook (useAllEmployees) is calling setEmployeeListUpdated(). This means your useEffect dependency will never change, and therefore only run once.
    Login or Signup to reply.
  3. Just simply move useAllEmployees hook out of the component and update the params in the definition and use the hook in your component

    const useAllEmployees = (employeeListUpdated) => {
        // keep the implementation
    };
    
    const YourComponent = () => {
      const [employeeListUpdated, setEmployeeListUpdated] = useState(false);
      const allEmployees = useAllEmployees(employeeListUpdated);
    
      // keep the implementation
    }
    

    Although the old code works, eslint keeps showing the error as sometimes it is not smart enough to detect a rule violation. But it is truly a good practice to NOT nest a hook inside a component since

    1. Hooks were born to separate the logic out of the component and for reusability.
    2. Also nesting it this way makes a hook will be redefined every time the component rerenders. Compared to the separate design, the hook will be recalled with another param set (way more efficient).
    3. In addition, if many places in your code have nesting patterns or the hook is too expensive in its declaration it can affect the performance.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search