'TypeError: history.push is not a function Why this show sometime

I don't understand why this error not come every time sometimes the code working and sometimes not working

const dispatch = useDispatch()

const userDetails = useSelector(state => state.userDetails)
const { error, loading, user } = userDetails

const userLogin = useSelector(state => state.userLogin)
const { userInfo } = userLogin

const userUpdateProfile = useSelector(state => state.userUpdateProfile)
const { success } = userUpdateProfile


useEffect(() => {
        if (!userInfo) {
            **history.push**(`/login`)
        }
        else{
            if(!user || !user.name || success){
                dispatch({ type: USER_UPDATE_DETAILS_RESET })
                dispatch(getUserDetails('profile'))
            }
            else{
                setName(user.name)
                setEmail(user.email) 
            }
        }
    }, [dispatch, history, userInfo, user, success ])


Solution 1:[1]

Add const history = useHistory(); at the top. After, you can check if its value is undefined.

Solution 2:[2]

Instead of history.push('/login').

Use this instead history('/login').

For this work, the useHistory is no longer available as one of the react-router-dom libraries,its now useNavigate.

Try this

import {useNavigate} from 'react-router-dom';
const navigate = useNavigate();
navigate('/login')

Solution 3:[3]

import { useHistory } from "react-router-dom";

const history = useHistory();

history.push(/login)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Axel de Arias
Solution 2 Cristik
Solution 3 bjbaskar