Reputation: 611
I use useEffect in App.tsx
import { useNavigate} from 'react-router-dom'
import { useDispatch } from 'react-redux';
const dispatch = useDispatch()
const navigate = useNavigate()
useEffect(() => {
const jwt = storage.getToken()
if(jwt) {
dispatch(asyncInit())
navigate('/profile')
}
}, [])
Without dependency dispatch and navigate React App shows a warning. But I can't put dispatch and navigate into dependency cuz every time redirect user to /profile navigate change state, this component rerender and it keep redirect to /profile/
Upvotes: 1
Views: 1887
Reputation: 66
I was having the same issue in my application and thought that it would be safe to ignore that warning, but looks like it is not. Since it changes the state (navigate), the hook will use its version from previous render. I think this might cause some issues later, not sure.
https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies
Upvotes: 1
Reputation: 1201
Yes you are right we can't put everything we use in dependency array so what you can do is put
//eslint-disable-next-line
above the dependency array. It will stop giving you warnings and there's nothing wrong with doing it.
import { useNavigate} from 'react-router-dom'
import { useDispatch } from 'react-redux';
const dispatch = useDispatch()
const navigate = useNavigate()
useEffect(() => {
const jwt = storage.getToken()
if(jwt) {
dispatch(asyncInit())
navigate('/profile')
}
//eslint-disable-next-line
}, [])
Upvotes: 2