I have the below code and as far as I'm concerned it only relies upon [page] yet, I am getting the error
React Hook useEffect has a missing dependency
I've seen similar questions about commenting out a line in your eslint file but
- I don't have an eslint file
- I would rather understand and resolve the issue
const fetchStarWarsInfo = async () => {
const response = await getData(
`https://swapi.dev/api/people/?page=${dontReturnZero(page)}`
);
dispatch(setCurrentCharacters(response.results));
};
useEffect(() => {
fetchStarWarsInfo();
}, [page]);
CodePudding user response:
Actually it might also ask you to put dispatch in dependencies and other stuff, so it's not so critical not to list all of the dependencies that he ask for.
Try to remove dispatch from your fetchStarWarsInfo and check. If error doesn't disappear, so try to remove also getData function.
You might also want to configure eslint for React, so those errors would have more information about error
CodePudding user response:
If fetchStarWarsInfo
is declared within the functional component, everytime state changes, the function is re-constructed and re-declared, therefore, it changes. Therefore the error message is notifying you that although the function is changing, it's not declared as a dependency. The problem though, is if you declare a function as a dependency, you can potentially create an infinite loop, since if you change state within the fetchStarWarsInfo
, the useEffect hook will have to continuously keep running, as a new instance of fetchStarWarsInfo
will be created.
The solutions to this are pretty straightforward. Declare the fetchStarWarsInfo
within the useEffect hook or split up the logic within the function, so you can declare it outside the functional component completely. Then handle state changes within the useEffect
hook. That way the function is declared only once, and state changes are handled within the hook, thereby causing no unwanted side effects
After doing this, you need to verify that all the functions used within fetchStarWarsInfo
are not continuously changing either. (i.e dontReturnZero
,setCurrCharacters
, etc). You can check this by commenting them out and seeing if the error disappears. If it does disappear, you'll need to include them in your dependency array for useEffect.
Example 1:
useEffect(() => {
const fetchStarWarsInfo = async () => {
const response = await getData(
`https://swapi.dev/api/people/?page=${dontReturnZero(page)}`
);
dispatch(setCurrentCharacters(response.results));
};
fetchStarWarsInfo();
}, [page, dispatch]);
Example 2:
const fetchStarWarsInfo = async (page) => {
const response = await getData(
`https://swapi.dev/api/people/?page=${dontReturnZero(page)}`
);
return response
};
const FunctionalComponent=() => {
const dispatch = useDispatch()
useEffect(() => {
fetchStarWarsInfo(page).then((data)=> dispatch(setCurrentCharacters(data.results));
}, [page, dispatch]);
}