Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I utilize eslint-disable-line to disable react-hooks/exhaustive-deps, but exempt particular props from being disabled not all of them?

I can turn that rule of for entire array:

useEffect(() => {
    if (id) {
        stableCallback(id);
        dynamicCallback(id);
    }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id, dynamicCallback]);

But my preference would be to achieve something along these lines (pseudocode):

useEffect(() => {
    if (id) {
        stableCallback(id);
        dynamicCallback(id);
    }
// eslint-disable-next-line react-hooks/exhaustive-deps stableCallback
}, [id, dynamicCallback]);

In my imagination, the usage of "stableCallback" does not trigger the warning, but if a new dependency emerges within it, I will see the warning about it (I know that if stableCallback is not changed then it should not matter - but that's only an example).

Is there a rule similar to exhaustive-deps, or any alternative approach that would allow me to utilize it in a similar manner?

I haven't found any alternative to it.

like image 989
Deykun Avatar asked Oct 29 '25 23:10

Deykun


1 Answers

You cannot do this and there is no rule for excluding a specific dependency. In fact, you don't have to follow Eslint, especially when it comes to including dependency, sometimes it suggests including values that you don't really want to include.

You should think of dependencies as data that once change value between renders, the corresponding hook is triggered.
If one dependency is immutable (string, number, boolean) then there is no problem but when it is mutable (object, array) then you have to memoize it using useMemo to avoid triggering the hook on every component render.

Now when you include a callback function as a dependency, this will make the hook run each time this function is recreated, I don't think you want to achieve that. maybe you just need to keep the callback function recreated each time it needs to, and trigger useEffect to run only when id is changed:

const dynamicCallback = useCallback((id) => {
  console.log(id + x + y);
},[x,y])

//...
useEffect(() => {
 if (id) {
   stableCallback(id);
   dynamicCallback(id);
 }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [id]);

This way, the most recent version of dynamicCallback will run each time id changes


If you really want to trigger useEffect every time dynamicCallback is recreated, maybe you could make it a simple function inside useEffect and include the necessary dependencies right there, so whenever the effect is triggered, the function is recreated and then called

useEffect(() => {
 const dynamicCallback = () => {
   console.log(id + x + y)
 }
 dynamicCallback();
}, [id, x, y]);
like image 96
Ahmed Sbai Avatar answered Nov 02 '25 23:11

Ahmed Sbai