Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React hooks warn me for missing dependencies

Suppose I am using useEffect to prefetch data on initial rendering:

function myComponent(props) {
    const { fetchSomething } = props;
    ...
    ...
    useEffect(() => {
        fetchSomething();
    }, []);
    ...
    ...
}

My linter warn me for "React Hook useCallback has missing dependencies". It wants me to put fetchSomething inside the dependencies array.
The issue is that even it fetchSomething is going to be changed, I don't want the component to refetch the data. And as I see it, most of the situations where useEffect uses a function, it doesn't really care whether the function is changed.
I don't want to turn off that warning and doesn't like to spread // eslint-disable-next-line react-hooks/exhaustive-deps all over my code.
What is the rational behind such behavior?
It makes me feel insecure while using hooks, as if I am doing something incorrect.

like image 365
Naor Avatar asked Aug 11 '26 21:08

Naor


1 Answers

You can use useRef or useMemo to store the value.

See https://stackoverflow.com/a/54963730/9351632

like image 78
Pieter Venter Avatar answered Aug 14 '26 10:08

Pieter Venter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!