Consider the following example:
const userRole = sessionStorage.getItem('role');
const { data, setData, type, setTableType } = useTable([]);
useEffect(() => {
const getData = async () => {
// fetch some data from API
const fetchedData = await axios('..');
if (userRole === 'admin') {
setData([...fetchedData, { orders: [] }]);
} else {
setData(fetchedData);
}
if (type === '1') {
setTableType('normal');
}
};
getData();
}, []);
I want to run this effect ONLY on mounting and that's it, I don't care whether the userRole
or setData
has changed or not!
So, Now my questions are:
- Why ESLint is complaining about
userRole
being missing in the dependencies array? Its not even a state! - Why ESLint is
complaining about
setData
being missing in the dependencies array isn't it will always be the same reference or does it change? - How to achieve what I want without upsetting the linter? Or should I straight slap the good old
// eslint-disable-line react-hooks/exhaustive-deps
line? Or this is absolutely barbaric? - Why this indicates a bug in my code? I want to run this effect only once with whatever is available initially.
EDIT:
Let me rephrase the question What If these variables change and I don't care about their new values? Especially when type
is getting updated in different places in the same file. I just want to read the initial value and run useEffect once how to achieve that?
react-hooks/exhaustive-deps warning
userRole
changes, won't the data be incorrect then? – PescarauserRole
is stored in sessionStorage and it will always be the same unless the user logged out and logged in with different account type – OutlawryuserRole
should be in the dependencies array. The code doesn't know the business logic of "it will always be the same". – PescaraReact.useState
does not change over time, butuseTable
appears to be a custom library; it doesn't know anything special aboutsetData
and so gives you the same warning as any other variable. – PescarauseEffect
once likecomponentDidMount
without upsetting the linter. – OutlawryuseTable
is a custom hook I wrote which hasstate
andsetState
and other functions that I expose. – OutlawryuseEffect
will only get called once. If these things ever do change, your code will be logically incorrect and will lead to subtle errors. I suggest following the lint rule; it is helping you here and preventing subtle potential bugs. – PescarauseEffect
will only ever run one time like you want. If you add the vals to the array, your code will then also be logically correct. – Pescaratype
to help delivering my point. Thistype
changes whenever the user clicks on a button to go to the next table. In this case If I added thetype
to dependency array it will get triggered which what I don't want! Can you check the post one last time and tell me what do you think? – Outlawry