Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

which is correct way to use navigate dependency in useEffect

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/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
  }, [])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading