React Useeffect Missing Dependecy?
Solution 1:
What i have to do ?
Either one of the two things the error says, or just remove the function and put the logic that's in it directly into your useEffect
callback, if you only ever use it from that callback.
Here's what the two options the error message gave you look like: Moving the loadAllAbout
function into your useEffect
callback:
useEffect(() => {
// ...code using `loadAllAbout` (here or after it, either is fine)...functionloadAllAbout() {
// ...
}
}, []);
Or using useCallback
or similar to make loadAllAbout
not a new function every time your component function runs:
const loadAllAbout = useCallback(() => {
// ...
}, []);
Solution 2:
Because loadAllAbout
is re-created on every render, adding it as a dependency will in fact cause your effect to run on every render.
The missing dependency warning can be safely ignored in some cases. Here, as your effect is only being run once to initialize some data, it should be fine.
If your component is going to re-render many times, memoizing loadAllAbout
and including it as a dependency would be a more complete solution, but this may not be necessary in your case.
Solution 3:
1. (Stopped working) Use function as useEffect callback
useEffect(loadAllAbout, [])
2. Declare function inside useEffect()
useEffect(() => {
functionloadAllAbout() {
...
}
loadAllAbout()
}, [])
3. Memoize with useCallback()
In this case, if you have dependencies in your function, you will have to include them in the useCallback dependencies array and this will trigger the useEffect again if the function's params change. Besides, it is a lot of boilerplate... So just pass the function directly to useEffect as in 1. useEffect(loadAllAbout, [])
.
const loadAllAbout= useCallback(() => {
...
}, [])
useEffect(() => {
loadAllAbout()
}, [loadAllAbout])
4. Disable eslint's warning
useEffect(() => {
loadAllAbout()
}, []) // eslint-disable-line react-hooks/exhaustive-deps
Solution 4:
Do exactly what the eslint plugin suggests: move the function inside useEffect and you have a clean dependancy array. loadAllAbout
is the kind of effect that's used once on mount, so useEffect is the perfect place for it.
Post a Comment for "React Useeffect Missing Dependecy?"