With React 16.8.6 (it was good on previous version 16.8.3), I get this error when I attempt to prevent an infinite loop on a fetch request
./src/components/Bu
You can set it directly as the useEffect callback:
useEffect(fetchBusinesses, [])
It will trigger only once, so make sure all the function's dependencies are correctly set (same as using componentDidMount/componentWillMount...
)
Edit 02/21/2020
Just for completeness:
useEffect
callback (as above)useEffect(fetchBusinesses, [])
useEffect()
useEffect(() => {
function fetchBusinesses() {
...
}
fetchBusinesses()
}, [])
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(fetchBusinesses, [])
.
const fetchBusinesses = useCallback(() => {
...
}, [])
useEffect(() => {
fetchBusinesses()
}, [fetchBusinesses])
useEffect(() => {
fetchBusinesses()
}, []) // eslint-disable-line react-hooks/exhaustive-deps