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
As the error says, you can’t use a state outside of the React Hook function.
A couple red flags I can spot with the little context provided:
const [employeeListUpdated, setEmployeeListUpdated] = useState(false);
(useAllEmployees)
is callingsetEmployeeListUpdated()
. This means your useEffect dependency will never change, and therefore only run once.Just simply move
useAllEmployees
hook out of the component and update the params in the definition and use the hook in your componentAlthough 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